欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ObjectMapper操作Json对象

程序员文章站 2022-07-12 16:28:59
...
实体类
public class Roots {

    private int rid = 11;
    private String name = "root";
    private List<Items> items;
	// Getter And Setter ....
}

public class Items {

    private int id = 1;
    private String name = "qq";

    public Items(int id, String name) {
        this.id = id;
        this.name = name;
    }
// Getter And Setter ...

测试代码
@Test
    public void testObjectMapper() throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        Roots roots = new Roots();
        Items items1 = new Items(2,"2");
        Items items2 = new Items(3,"3");
        List<Items> list = new ArrayList<>();
        list.add(items1); list.add(items2);
        roots.setItems(list);

        String json = JsonUtils.convertObjectToJson(roots);
        System.out.println(json);
        JsonNode jsonNode = objectMapper.readTree(json);
        Iterator<Map.Entry<String, JsonNode>> fields = jsonNode.fields();
        while (fields.hasNext()){
            Map.Entry<String, JsonNode> next = fields.next();
            if (next.getKey().equals("items")) {
                JsonNode value = next.getValue();
                if (value.isArray()) {
                    System.out.println(value.get(0).get("name"));
                }
            }

        }
    }

最终打印结果:
{“rid”:11,“name”:“root”,“items”:[{“id”:2,“name”:“2”},{“id”:3,“name”:“3”}]}
“2”

根据我自己的条件最终获取到了 数组中的 name属性的值

相关标签: Json json