**How to convert Java object to Pretty Print JSON :** Converting Java object to JSON is a little complex work in Java. We can use the third party api to make this easy.
Jackson is one of the most popular api for JAVA JSON processing. Jackson api is fast, convenient and high performance api for json processing. We can convert Java object to json object and vice versa.
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 :
com.fasterxml.jackson.core
jackson-databind
2.2.3
In our example we are converting Java Object to JSON object.
**Example of converting Java Object to Pretty print JSON Output :**
**Employee.java**
package com.evon.jakson.conversion;
public class Employee {
private long id;
private String name;
private String occupation;
Employee(){
}
Employee(long id, String name, String occupation){
this.id=id;
this.name=name;
this.occupation=occupation;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
@Override
public String toString(){
return getId() + ", "+getName()+", "+getOccupation();
}
}
Employee.java is a model object which we will convert to Pretty print JSON object. Now we will write the code to convert that Employee object to Pretty print JSON output.
**JavaObjectToPrettyJSON.java**
package com.evon.jakson.conversion;
import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JavaObjectToPrettyJSON {
public static void main(String[] args) {
String filePath = "/home/sumit/prettyEmployee.json";
Employee crocodile = new Employee(1, "Sumit", "Software Engineer");
ObjectMapper objectMapper = new ObjectMapper();
try {
File file = new File(filePath);
if(!file.exists())file.createNewFile();
objectMapper.writerWithDefaultPrettyPrinter().writeValue(
new File(filePath), crocodile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
The above code will create a prettyEmployee.json file and save the employee object to this document as a formatted json object.Following is the view how the file will look like :
**Output File :** /home/sumit/prettyEmployee.json
{
"id" : 1,
"name" : "Sumit",
"occupation" : "Software Engineer"
}
0 Comment(s)