Java 如何(完全)将json反序列化为通用列表?
当使用Java 如何(完全)将json反序列化为通用列表?,java,generics,jackson,json-deserialization,Java,Generics,Jackson,Json Deserialization,当使用ObjectMapper将json字符串转换为实体时,我可以将其设置为通用的: public <E> E getConvertedAs(String body, Class<E> type) throws IOException { return mapper.readValue(body, type); } publicstaticlist fromJson(字符串中的字符串,类中的类型)抛出JsonParseException、JsonMappingE
ObjectMapper
将json字符串
转换为实体时,我可以将其设置为通用的:
public <E> E getConvertedAs(String body, Class<E> type) throws IOException {
return mapper.readValue(body, type);
}
publicstaticlist fromJson(字符串中的字符串,类中的类型)抛出JsonParseException、JsonMappingException、IOException{
返回新的ObjectMapper().readValue(在_字符串中,新的TypeReference(){});
}
在我的电脑上编译。
请注意,我还没有测试它。此方法有助于将
json
读取到对象或集合:
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;
}
}
public类JsonUtil{
私有静态最终ObjectMapper mapper=新ObjectMapper();
公共静态T对象(字符串json,类型引用typeRef){
T=零;
试一试{
t=mapper.readValue(json,typeRef);
}捕获(IOE异常){
e、 printStackTrace();
}
返回t;
}
}
阅读json以列出:
List<Device> devices= JsonUtil.toObject(jsonString,
new TypeReference<List<Device>>() {});
List devices=JsonUtil.toObject(jsonString,
新类型引用(){});
将json读取到对象:
Device device= JsonUtil.toObject(jsonString,
new TypeReference<Device>() {});
Device Device=JsonUtil.toObject(jsonString,
新类型引用(){});
也许newtypereference(){}
?@JeremyGrandE
是我的EntryType
,这就是我的LinkedHashMap列表。条目
请查看我对您评论的回复。它进行编译,但返回LinkedHashMap.Entry的列表
什么是ObjectMapper?那是导入库中的一个吗?我在这个问题上有各种各样的错误。
public <E> List<E> getConvertedListAs(String body, Class<E> type) {
mapper.readValue(body, new TypeReference<List<type>>() {}); // Doesn't compile
}
public static <E> List<E> fromJson(String in_string, Class<E> in_type) throws JsonParseException, JsonMappingException, IOException{
return new ObjectMapper().readValue(in_string, new TypeReference<List<E>>() {});
}
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;
}
}
List<Device> devices= JsonUtil.toObject(jsonString,
new TypeReference<List<Device>>() {});
Device device= JsonUtil.toObject(jsonString,
new TypeReference<Device>() {});