In the Jackson library, we can use the Tree Model to represent the JSON structure and perform the CRUD operations via JsonNode. This Jackson Tree Model is useful, especially in cases where a JSON structure does not map to Java classes. We can create a JSON in the Jackson library using the JsonNodeFactory, it can specify the methods for getting access to Node instances as well as the basic implementation of the methods. We can use the set() and put() methods of ObjectNode class to populate the data.
Syntax
public class JsonNodeFactory extends Object implements Serializable
Example
import java.io.*; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.node.*; public class JacksonTreeModelTest { public static void main(String args[]) throws IOException { JsonNodeFactory factory = new JsonNodeFactory(false); ObjectMapper mapper = new ObjectMapper(); ObjectNode employee = factory.objectNode(); employee.put("empId", 125); employee.put("firstName", "Raja"); employee.put("lastName", "Ramesh"); ArrayNode technologies = factory.arrayNode(); technologies.add("Python").add("Java").add("SAP"); employee.set("technologies", technologies); System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee)); } }
Output
{ "empId" : 125, "firstName" : "Raja", "lastName" : "Ramesh", "technologies" : [ "Python", "Java", "SAP" ] }