大家好,欢迎来到IT知识分享网。
【ObjectMapper的依赖】
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.4</version> </dependency>
【待处理的json文】
{ "name": "Moft", "count": 100, "nicknames": [ "Microsoft", "moft", "Mft", "Bill's company" ], "emps": [ { "id": 1, "name": "Andy" }, { "id": 2, "name": "Bill" }, { "id": 3, "name": "Cindy" }, { "id": 4, "name": "Dougalas" } ] }
【读取和处理程序】
RestTemplate restTemplate = new RestTemplate(); String json = restTemplate.getForObject("http://localhost:8080/showWelcome/",String.class); ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(json); JsonNode nickNode=root.get("nicknames"); // json转数组 String json1=nickNode.toString(); System.out.println(json1); List<String> ls1 = mapper.readValue(json1, List.class); for(String nick:ls1){ System.out.println(nick); } JsonNode empsNode=root.get("emps"); // json转对象数组 String json2=empsNode.toString(); System.out.println(json2); List<Employee> ls2 = mapper.readValue(json2, new TypeReference<List<Employee>>(){}); for(Employee employee:ls2){ System.out.println(employee); }
【Employee类】
package com.hy; public class Employee { private int id; private String name; public Employee() { this(-1, ""); } public Employee(int id,String name) { this.id=id; this.name=name; } public String toString(){ return "EMP:"+id+"_"+name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
【输出】
["Microsoft","moft","Mft","Bill's company"] Microsoft moft Mft Bill's company [{"id":1,"name":"Andy"},{"id":2,"name":"Bill"},{"id":3,"name":"Cindy"},{"id":4,"name":"Dougalas"}] EMP:1_Andy EMP:2_Bill EMP:3_Cindy EMP:4_Dougalas
END
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/29097.html