how to convert JSONArray to List of Object using camel-jackson(如何使用骆驼杰克逊将 JSONArray 转换为对象列表)
问题描述
我的 json 数组字符串如下
Am having the String of json array as follow
{"Compemployes":[
{
"id":1001,
"name":"jhon"
},
{
"id":1002,
"name":"jhon"
}
]}
我想将此 jsonarray 转换为 List<Empolyee>
.为此,我添加了 maven 依赖项camel-jackson
",并为员工编写了 pojo 类.但是当我尝试运行下面的代码时
i want to convert this this jsonarray to List<Empolyee>
. for this i had added the the maven dependency "camel-jackson
" and also write the pojo class for employee . but when i try to run my below code
ObjectMapper mapper = new ObjectMapper();
List<Employe> list = mapper.readValue(jsonString, TypeFactory.collectionType(List.class, Employe.class));
我遇到了以下异常.
org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
at [Source: java.io.StringReader@43caa144; line: 1, column: 1]
有人可以告诉我缺少什么或做错了什么
can someone pls tell what am missing or doing anyting wrong
推荐答案
问题不在于你的代码,而在于你的 json:
The problem is not in your code but in your json:
{"Compemployes":[{"id":1001,"name":"jhon"}, {"id":1002,"name":"jhon"}]}
this 表示一个包含属性 Compemployes 的对象,该属性是员工.在这种情况下,您应该像这样创建该对象:
this represents an object which contains a property Compemployes which is a list of Employee. In that case you should create that object like:
class EmployeList{
private List<Employe> compemployes;
(with getter an setter)
}
反序列化 json 只需:
and to deserialize the json simply do:
EmployeList employeList = mapper.readValue(jsonString,EmployeList.class);
如果您的 json 应该直接表示员工列表,它应该如下所示:
If your json should directly represent a list of employees it should look like:
[{"id":1001,"name":"jhon"}, {"id":1002,"name":"jhon"}]
最后一句话:
List<Employee> list2 = mapper.readValue(jsonString,
TypeFactory.collectionType(List.class, Employee.class));
TypeFactory.collectionType
已被弃用,您现在应该使用类似:
TypeFactory.collectionType
is deprecated you should now use something like:
List<Employee> list = mapper.readValue(jsonString,
TypeFactory.defaultInstance().constructCollectionType(List.class,
Employee.class));
这篇关于如何使用骆驼杰克逊将 JSONArray 转换为对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用骆驼杰克逊将 JSONArray 转换为对象列表
基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 降序排序:Java Map 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01