How to traverse JSON object using Jackson api: Jackson api is used to read, write and update the Json object. We can traverse the JSON object using the Jackson api. Jackson provides the Tree model to traverse the JSON document, so we can traverse the json object node by node .
We can pick the nodes one by one and can add new node, update value and also can remove nodes. So If you want to update the json document traverse the document using Tree model.
To use Jackson api in our project we need to download the following jars :
jackson-databind-2.2.3.jar
jackson-core-2.2.3.jar
jackson-annotations-2.2.3.jar
Or we can use maven dependency in our project, put following code in pom.xml :
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.3</version>
</dependency>
In our example we are traversing json tree with Jackson api and updating the object.
Example to update JSON object :
We will write the code to traverse and update the Json objects saved in the file.
package com.evon.jakson.conversion;
import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class UpdateJsonObject {
public static void main(String[] args) throws JsonProcessingException, IOException {
String filePath = "/home/user/employee.json";
String updateFilePath = "/home/user/updateEmployee.json";
ObjectMapper objectMapper = new ObjectMapper();
//create JsonNode
JsonNode rootNode = objectMapper.readTree(new File(filePath));
//update JSON data
((ObjectNode) rootNode).put("id", 500);
//add new key value
((ObjectNode) rootNode).put("name", "Rahul Kumar");
//remove existing key
((ObjectNode) rootNode).remove("occupation");
objectMapper.writeValue(new File(updateFilePath), rootNode);
}
}
In the above code we are passing a file called employee.json which is having the json object and readTree() method of ObjectMapper will allow you to traverse the json nodes and after updating nodes we will save it in a file called updateEmployee.json .
Output :
updateEmployee.json
{"id":500,"name":"Rahul Kumar"}
0 Comment(s)