
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create JSON Using Jackson Tree Model in Java
To create a JSON using the Jackson Tree Model in Java, we can use the ObjectMapper class. The ObjectMapper class is part of the Jackson library and is used to convert Java objects to JSON and vice versa.
To use the Jackson library, we need to add it to our project. If you are using Maven, add this to your pom.xml file:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.0</version> </dependency>
If you are not using Maven, you can download the jar file from here.
Creating a JSON using Jackson Tree Model in Java
Following are the steps to create a JSON using the Jackson Tree Model in Java:
- Create a class Person with fields for name and age.
- Then create an instance of the ObjectMapper class.
- Next, create a JsonNode object using the ObjectMapper.
- Then create a ObjectNode object using the ObjectMapper.
- Then add fields to the ObjectNode object using the put() method.
- Finally, convert the ObjectNode object to a JSON string using the writeValueAsString() method of the ObjectMapper.
- Print the JSON string.
Example
Following is the code to create a JSON using the Jackson Tree Model in Java:
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class JsonGeneratorExample { public static void main(String[] args) throws IOException { // Create an ObjectMapper instance ObjectMapper objectMapper = new ObjectMapper(); // Create a JsonNode object using the ObjectMapper JsonNode jsonNode = objectMapper.createObjectNode(); // Create an ObjectNode object using the ObjectMapper ObjectNode objectNode = (ObjectNode) jsonNode; // Add fields to the ObjectNode object objectNode.put("name", "Ansh"); objectNode.put("age", 23); // Convert the ObjectNode object to a JSON string String jsonString = objectMapper.writeValueAsString(objectNode); // Print the JSON string System.out.println(jsonString); } }
Output
{"name":"Ansh","age":23}
Advertisements