Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ClassCastException when convert json to list of objects

Tags:

java

json

I am using Jackson library to process json data.

I have created a generic function to convert json string to a model class object:

public <T> T parseJsonToObject(String jsonStr, Class<T> clazz) {
    ObjectMapper mapper = new ObjectMapper();
    try {
      return mapper.readValue(jsonStr, clazz);
    } catch (Exception e) {

    }

     return null; 
}

I have a Person class:

public class Person{
   @JsonProperty("first_name")
   private String firstName;

   @JsonProperty("last_name")
   private String lastName;
   //Getter & Setters ...
}

I got server response which is a List of persons:

[{"first_name":"John","last_name":"Smith"},{"first_name":"Kate","last_name":"Green"}]

My String jsonPersonsStr holds the above json string.

Now I try to use my function to directly convert the json string to a List of Person:

List<Person> persons = parseJsonToObject(jsonPersonsStr, ArrayList.class);

But I got Exception:

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.my.models.Person

How to modify my generic function to get rid of this Exception?

like image 430
Leem.fin Avatar asked Oct 21 '22 11:10

Leem.fin


1 Answers

The best you can probably do is to support one generic method for Collection types, and possibly others for non-Collection types.

Here's a working version of the generic Collection method:

import org.codehaus.jackson.map.type.TypeFactory;

//...

@SuppressWarnings({ "deprecation", "rawtypes" })
public static <E, T extends Collection> T parseJsonToObject(String jsonStr, Class<T> collectionType, Class<E> elementType) {
    ObjectMapper mapper = new ObjectMapper();
    try {
        return mapper.readValue(jsonStr, TypeFactory.collectionType(collectionType, elementType));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null; 
}

Then you would call this like:

List<Person> persons = parseJsonToObject(s, ArrayList.class, Person.class);
like image 56
superEb Avatar answered Oct 23 '22 09:10

superEb