1.添加依赖
<!-- jackson framework -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.8.5</version>
</dependency>
2.我们可以像操作html或者xml那样读写json
@Test
public void Test4() {
try {
BufferedReader file = new BufferedReader(new FileReader("C:\\Users\\Administrator\\Desktop\\java\\User.json"));
ObjectMapper map = new ObjectMapper();
JsonNode jsonnode = map.readTree(file);
//指定路劲的node
JsonNode names = jsonnode.path("name");
//读取指定路径的数据
String na = names.getTextValue();
System.out.println(na);
JsonNode mess = jsonnode.path("messages");
Iterator<JsonNode> itr = mess.getElements();
while(itr.hasNext()){
System.out.println(itr.next().getTextValue());
}
//更新
((ObjectNode)jsonnode).put("name","update");
((ObjectNode)jsonnode).remove("age");
map.writeValue(new File("C:\\Users\\Administrator\\Desktop\\java\\User.json"), jsonnode);
//
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}