问题描述
我正在使用杰克逊库来处理json数据.
I am using Jackson library to process json data.
我创建了一个泛型函数,用于将json字符串转换为模型类对象:
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;
}
我有一个Person类:
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"}]
我的String jsonPersonsStr
拥有上面的json字符串.
My String jsonPersonsStr
holds the above json string.
现在我尝试使用我的函数将json字符串直接转换为人员列表:
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);
但是我有一个例外:
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?
推荐答案
您可能要做的最好的事情就是为Collection
类型支持一种通用方法,为非Collection
类型支持其他通用方法.
The best you can probably do is to support one generic method for Collection
types, and possibly others for non-Collection
types.
这是通用Collection
方法的工作版本:
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;
}
然后您将这样称呼:
List<Person> persons = parseJsonToObject(s, ArrayList.class, Person.class);
这篇关于将json转换为对象列表时发生ClassCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!