如何使用Jackson反序列化对象数组这个Jackson数据绑定文档指示Jackson支持反序列化“所有受支持类型的数组”,但我无法确定确切的语法。对于单个对象,我会这样做://json input{
"id" : "junk",
"stuff" : "things"}//JavaMyClass instance = objectMapper.readValue(json, MyClass.class);现在,对于一个数组,我想这样做://json input[{
"id" : "junk",
"stuff" : "things"},{
"id" : "spam",
"stuff" : "eggs"}]//JavaList<MyClass> entries = ?有人知道没有魔法命令吗?如果没有,解决办法是什么?
3 回答
慕虎7371278
TA贡献1802条经验 获得超4个赞
import com.fasterxml.jackson.databind.ObjectMapper;// in play 2.3ObjectMapper mapper = new ObjectMapper();
MyClass[] myObjects = mapper.readValue(json, MyClass[].class);
List<MyClass> myObjects = mapper.readValue(jsonInput, new TypeReference<List<MyClass>>(){});
List<MyClass> myObjects = mapper.readValue(jsonInput, mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class));
一只名叫tom的猫
TA贡献1906条经验 获得超3个赞
public static <T> List<T> parseJsonArray(String json, Class<T> classOnWhichArrayIsDefined) throws IOException, ClassNotFoundException { ObjectMapper mapper = new ObjectMapper(); Class<T[]> arrayClass = (Class<T[]>) Class.forName("[L" + classOnWhichArrayIsDefined.getName() + ";"); T[] objects = mapper.readValue(json, arrayClass); return Arrays.asList(objects);}
添加回答
举报
0/150
提交
取消