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

查看:186
本文介绍了尝试在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:无法反序列化entitylayer.Detail实例的START_ARRAY令牌

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格式的列表,这是制作的部分我参与了 jackson教程新文件(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(即无类型地图),如上所述。

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天全站免登陆