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属性的值
上一篇: 链式编程思想理解