In Jackson, you can use “Tree Model” to represent JSON, and perform the read and write operations via “
JsonNode
“, it is similar to DOM tree for XML. See code snippet : ObjectMapper mapper = new ObjectMapper();
BufferedReader fileReader = new BufferedReader(
new FileReader("c:\\user.json"));
JsonNode rootNode = mapper.readTree(fileReader);
/*** read value from key "name" ***/
JsonNode nameNode = rootNode.path("name");
System.out.println(nameNode.getTextValue());
This time, we show you how to read the JSON string from “file.json” into a “Tree“, and also how to read and and update those values via
JsonNode
.
File : file.json
{
"age" : 29,
"messages" : [ "msg 1", "msg 2", "msg 3" ],
"name" : "harit"
}
See full example, it should be self-explanatory.
package com;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ObjectNode;
public class JacksonTreeNodeExample {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
try {
BufferedReader fileReader = new BufferedReader(
new FileReader("c:\\user.json"));
JsonNode rootNode = mapper.readTree(fileReader);
/*** read ***/
JsonNode nameNode = rootNode.path("name");
System.out.println(nameNode.getTextValue());
JsonNode ageNode = rootNode.path("age");
System.out.println(ageNode.getIntValue());
JsonNode msgNode = rootNode.path("messages");
Iterator<JsonNode> ite = msgNode.getElements();
while (ite.hasNext()) {
JsonNode temp = ite.next();
System.out.println(temp.getTextValue());
}
/*** update ***/
((ObjectNode)rootNode).put("nickname", "new nickname");
((ObjectNode)rootNode).put("name", "updated name");
((ObjectNode)rootNode).remove("age");
mapper.writeValue(new File("c:\\user.json"), rootNode);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output
harit
29
msg 1
msg 2
msg 3
And the file “c:\\file.json” is updated with following new content :
{
"messages" : [ "msg 1", "msg 2", "msg 3" ],
"name" : "updated name",
"nickname" : "new nickname"
}
0 comments:
Post a Comment