【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