问题描述
当使用 ObjectMapper
将json String
转换为实体时,我可以将其设为通用: / p>
When using an ObjectMapper
to transform a json String
into an entity, I can make it generic as:
public <E> E getConvertedAs(String body, Class<E> type) throws IOException {
return mapper.readValue(body, type);
}
现在让我说我想读集合。我可以这样做:
Now let's say I want to read collections. I can do:
List<SomeEntity> someEntityList = asList(mapper.readValue(body, SomeEntity[].class));
List<SomeOtherEntity> someOtherEntityList = asList(mapper.readValue(body, SomeOtherEntity[].class));
我想写一个上述的等效方法,但是对于集合。由于你不能在java中使用泛型数组,所以这样的东西不起作用:
I would like to write an equivalent method of the above, but for collections. Since you can't have generic arrays in java, something like this won't work:
public <E> List<E> getConvertedListAs(String body, Class<E> type) {
return mapper.readValue(body, type[].class);
}
有一个几乎可行的解决方案:
Here there is a solution that almost works:
mapper.readValue(jsonString, new TypeReference<List<EntryType>>() {});
问题是它没有反序列化为 E
,但 LinkedHashMap.Entry
。有什么方法可以更进一步,如下所示?
The problem is that it doesn't deserialize into a list of E
, but of LinkedHashMap.Entry
. Is there any way of going going a step further, something like the following?
public <E> List<E> getConvertedListAs(String body, Class<E> type) {
mapper.readValue(body, new TypeReference<List<type>>() {}); // Doesn't compile
}
推荐答案
此方法可以帮助读取 json
到一个或多个对象:
This method can help to read json
to an object or collections:
public class JsonUtil {
private static final ObjectMapper mapper = new ObjectMapper();
public static <T>T toObject(String json, TypeReference<T> typeRef){
T t = null;
try {
t = mapper.readValue(json, typeRef);
} catch (IOException e) {
e.printStackTrace();
}
return t;
}
}
读json到列表:
List<Device> devices= JsonUtil.toObject(jsonString,
new TypeReference<List<Device>>() {});
将json读取到对象:
Read json to object:
Device device= JsonUtil.toObject(jsonString,
new TypeReference<Device>() {});
这篇关于如何(完全)将json反序列化为通用列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!