猿问

如何使用Jackson反序列化对象数组

如何使用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 = ?

有人知道没有魔法命令吗?如果没有,解决办法是什么?


PIPIONE
浏览 2358回答 3
3回答

慕虎7371278

首先创建一个映射器:import&nbsp;com.fasterxml.jackson.databind.ObjectMapper;//&nbsp;in&nbsp;play&nbsp;2.3ObjectMapper&nbsp;mapper&nbsp;=&nbsp;new&nbsp;ObjectMapper();作为阵列:MyClass[]&nbsp;myObjects&nbsp;=&nbsp;mapper.readValue(json,&nbsp;MyClass[].class);作为清单:List<MyClass>&nbsp;myObjects&nbsp;=&nbsp;mapper.readValue(jsonInput,&nbsp;new&nbsp;TypeReference<List<MyClass>>(){});另一种指定列表类型的方法:List<MyClass>&nbsp;myObjects&nbsp;=&nbsp;mapper.readValue(jsonInput,&nbsp;mapper.getTypeFactory().constructCollectionType(List.class,&nbsp;MyClass.class));

尚方宝剑之说

从…尤金·茨霍夫List<MyClass>&nbsp;myObjects&nbsp;=&nbsp;Arrays.asList(mapper.readValue(json,&nbsp;MyClass[].class))这个解决办法对我来说似乎是最好的。

一只名叫tom的猫

关于一般执行:public&nbsp;static&nbsp;<T>&nbsp;List<T>&nbsp;parseJsonArray(String&nbsp;json, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Class<T>&nbsp;classOnWhichArrayIsDefined)&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;throws&nbsp;IOException,&nbsp;ClassNotFoundException&nbsp;{ &nbsp;&nbsp;&nbsp;ObjectMapper&nbsp;mapper&nbsp;=&nbsp;new&nbsp;ObjectMapper(); &nbsp;&nbsp;&nbsp;Class<T[]>&nbsp;arrayClass&nbsp;=&nbsp;(Class<T[]>)&nbsp;Class.forName("[L"&nbsp;+&nbsp;classOnWhichArrayIsDefined.getName()&nbsp;+&nbsp;";"); &nbsp;&nbsp;&nbsp;T[]&nbsp;objects&nbsp;=&nbsp;mapper.readValue(json,&nbsp;arrayClass); &nbsp;&nbsp;&nbsp;return&nbsp;Arrays.asList(objects);}
随时随地看视频慕课网APP

相关分类

Java
我要回答