尝试在 Java 中使用 Jackson 时出现问题 [英] Issue when trying to use Jackson in java

查看:26
本文介绍了尝试在 Java 中使用 Jackson 时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Jackson 将一些 JSON 数据转换为 Java 对象,准确地说是一个对象列表,但出现此错误:

I'm trying to use Jackson to convert some JSON data into Java objects ,a list of objects to be precise,but I get this error:

org.codehaus.jackson.map.JsonMappingException:无法从 START_ARRAY 令牌中反序列化 entitylayer.Detail 的实例

org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of entitylayer.Detail out of START_ARRAY token

这是代码:

 ObjectMapper mapper = new ObjectMapper(); 
 List<Detail> lcd = (List<Detail>) mapper.readValue(ld, Detail.class);

ld 是 Json 格式的列表,这是让我在 杰克逊教程.new File("user.json") 代表什么?我假设这是我想要转换的 json 格式的字符串,这就是我使用 ld 的原因.

ld is the list in Json format, this is the part that makes me comfused in the jackson tutorial. what does new File("user.json") represent? I assumed that was the string in json format I wanted to convert, that's why I used ld.

希望你能帮我解决

推荐答案

来自您链接的教程(其他集合的工作方式相同):

From the tutorial you linked (other Collections work the same way):

因此,如果要将数据绑定到 Map 中,则需要使用:

So if you want to bind data into a Map you will need to use:

Map<String,User> result = mapper.readValue(src, new TypeReference<Map<String,User>>() { });

TypeReference 只需要传递泛型类型定义(在这种情况下通过任意内部类):重要的部分是 > 定义要绑定到的类型.

where TypeReference is only needed to pass generic type definition (via anynomous inner class in this case): the important part is > which defines type to bind to.

如果你不这样做(只是传递 Map.class),调用就相当于绑定到 Map(即无类型"Map),如上所述.

If you don't do this (and just pass Map.class), call is equivalent to binding to Map (i.e. "untyped" Map), as explained above.

如果你坚持用勺子喂食:

If you insist on being spoon fed:

List<Detail> lcd = mapper.readValue(ld, new TypeReference<List<Detail>>() {});

这篇关于尝试在 Java 中使用 Jackson 时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆