反序列化内部JSON对象

编程入门 行业动态 更新时间:2024-10-26 06:28:04
本文介绍了反序列化内部JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个类POJO

Class Pojo { String id; String name; //getter and setter }

我有一个类似的json

I have a json like

{ "response" : [ { "id" : "1a", "name" : "foo" }, { "id" : "1b", "name" : "bar" } ] }

我使用Jackson ObjectMapper进行反序列化。如何在不创建任何其他父类的情况下获得 List< Pojo> ?

I am using Jackson ObjectMapper for deserialization. How can I get List<Pojo> without creating any other parent class?

如果不可能,则是有可能获得 Pojo 对象,它只包含json字符串的第一个元素,即在这种情况下 id =1a和 name =foo?

If it is not possible, is it possible to get Pojo object which holds just first element of json string i.e. in this case id="1a" and name="foo"?

推荐答案

您首先需要获取数组

String jsonStr = "{\"response\" : [ { \"id\" : \"1a\", \"name\" : \"foo\"},{ \"id\" : \"1b\",\"name\" : \"bar\" } ]}"; ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(jsonStr); ArrayNode arrayNode = (ArrayNode) node.get("response"); System.out.println(arrayNode); List<Pojo> pojos = mapper.readValue(arrayNode.toString(), new TypeReference<List<Pojo>>() {}); System.out.println(pojos);

打印(带 toString())

[{"id":"1a","name":"foo"},{"id":"1b","name":"bar"}] // the json array [id = 1a, name = foo, id = 1b, name = bar] // the list contents

更多推荐

反序列化内部JSON对象

本文发布于:2023-11-26 17:32:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634522.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   序列化   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!