Jackson convert object to JSON example and convert json to object example. Learn to use jackson objectmapper to populate java object from json string and write json string from java object.
Jackson is used to convert java object to json, and convert json to java object. In this quick jackson tutorial, I am giving examples of converting java objects to/from json programmatically.
Table of Contents 1. Jackson maven dependency 2. Convert Java object to JSON 3. Pretty print JSON 4. Convert JSON to Java object
Before jumping into code examples, lets define a simple pojo class which we will use in this example for conversion purpose.
public class Employee { private Integer id; private String firstName; private String lastName; public Employee(){ } public Employee(Integer id, String firstName, String lastName, Date birthDate){ this.id = id; this.firstName = firstName; this.lastName = lastName; } //Getters and setters @Override public String toString() { return "Employee [id=" + id + ", firstName=" + firstName + ", " + "lastName=" + lastName + "]"; } }
1. Jackson dependency
You can add Jackson dependency in two ways depending on your project type.
1.1. Maven based project
Add following dependency in your pom.xml file.
<dependencies> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.6</version> </dependency> </dependencies>
1.2. For ANT or other project types
For non-Maven use cases, you download jars from Central Maven repository.
2. Jackson ObjectMapper
ObjectMapper is the main api used for data-binding. It comes with several reader/writer methods to preform the conversion from/to Java and JSON. It will use instances of JsonParser
and JsonGenerator
for implementing actual reading/writing of JSON.
2.1. Syntax to convert json to object
Use below sample syntax to read JSON and populate java objects.
ObjectMapper mapper = new ObjectMapper(); Object value = mapper.readValue(jsonSource , javaObject);
jsonSource
– The input source which will fetch the json string.javaObject
– The target Java object which needs to be populated.
2.2. Syntax to convert object to json
Use below sample syntax to write java object to json string.
ObjectMapper mapper = new ObjectMapper(); Object value = mapper.writeValue(jsonTarget, javaObject);
jsonTarget
– The output target where json string will be written.javaObject
– The source Java object which needs to be converted to json.
3. Jackson convert object to JSON
To convert the employee object and write it to some file, to can use below code.
package test.jackson; import java.io.File; import java.io.IOException; import java.util.Date; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; public class JavaToJSONExample { public static void main(String[] args) { @SuppressWarnings("deprecation") Employee employee = new Employee(1, "Lokesh", "Gupta", new Date(1981,8,18)); ObjectMapper mapper = new ObjectMapper(); try { mapper.writeValue(new File("c://temp/employee.json"), employee); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
Program Output.
{"id":1,"firstName":"Lokesh","lastName":"Gupta"}
4. Jackson pretty print JSON output
If you look at above output, then the output written in text file is very raw and not formatted. You can write a formatted JSON content using defaultPrettyPrintingWriter()
writerWithDefaultPrettyPrinter
instance like below:
package test.jackson; import java.io.File; import java.io.IOException; import java.util.Date; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; public class JavaToPrettyJSONExample { public static void main(String[] args) { @SuppressWarnings("deprecation") Employee employee = new Employee(1, "Lokesh", "Gupta", new Date(1981,8,18)); ObjectMapper mapper = new ObjectMapper(); try { mapper.defaultPrettyPrintingWriter().writeValue(new File("c://temp/employee.json"), employee); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
Program Output.
{ "id" : 1, "firstName" : "Lokesh", "lastName" : "Gupta" }
5. Jackson convert JSON to Java object
To convert a json string to java object (e.g. Employee object) use below code:
package test.jackson; import java.io.File; import java.io.IOException; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; public class JSONToJavaExample { public static void main(String[] args) { Employee employee = null; ObjectMapper mapper = new ObjectMapper(); try { employee = mapper.readValue(new File("c://temp/employee.json"), Employee.class); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println(employee); } }
Program Output.
Employee [id=1, firstName=Lokesh, lastName=Gupta]
Employee.java
in our case). Jackson uses default constructor to create the instances of java class using reflection. If default constructor is not provided, then you will get JsonMappingException
in runtime.Happy Learning !!
dhanaraj
“{“timestamp”:”2019-07-29T06:53:14.290+0000″,”status”:400,”error”:”Bad Request”,”message”:”
JSON parse error: Cannot deserialize instance of `java.util.Date` out of START_OBJECT token; nested exception is
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.Date`
out of START_OBJECT token\n at [Source: (PushbackInputStream);
hai how to solve the above problem
Lokesh Gupta
Try this solution.
Shikha Singh
Getter setters are missing in Employee.java due to while mapper.readValue() won’t work
Lokesh Gupta
They are removed for brevity. I have added comment in code “//Getters and setters” for this reason only.
Bala
While passing autowired object for json parsing,
msg:com.fasterxml.jackson.databind.JsonMappingException: Direct self-reference leading to cycle (through reference chain:
kichu
(“$BEO,2.3,1105,V837152325,1,250417172030,110,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0”) i want split the comma seperated string into 3 values in each substring later i want to convert each sub string to json. how to do tat?.
Jon
Hello, please:
How may I accomplish the same with BOTH a Model bean and a managed bean that connects the MODEL to a remote MySQL data source?
https://stackoverflow.com/questions/41142802/jsf-managed-bean-accessing-mysql-remote-database-how-to-create-json-array-to-f
Any suggestions greatly appreciated.
Jon
Lokesh Gupta
Link seems dead.
Rajesh
Hi Lokesh, i have this json file can u plz tell how to convert to json
{
“ImplCreateBanRestOutput”:{
“baseOutput”:{
“ban”:””,
“statusCodes”:[
{
“status”:true,
“activityType”:””,
“additionalInfo”:””,
“errorCode”:””
},
{
“status”:true,
“activityType”:””,
“additionalInfo”:””,
“errorCode”:””
}
],
“responseInfo”:{
“code”:””,
“serverTS”:”2016-03-01T13:56:51.805+0200″,
“messageId”:””
}
}
}
}
Lokesh Gupta
It’s already json, dear.
Rajesh
conveting to java object Lokesh
Mickael
Hello,
I want to send from an external app a json object POST API . How to make the API understands that the parameter is a JSON object and the interpreter ?
thanks in advance
Lokesh Gupta
Use HTTP header “Content-type” in request and set it’s value to “application/json”.
alok singh
how to convert csv file to json file in java dynamically(csv file upload and then convert in json file using java)
Manish
Hi Lokesh,
Thanks for sharing such a nice tutorial..
I am using jackson library to parse JSON to POJO
Here I am in trouble while parsing….My json is dynamically changed..
I am using REST api to get json response..
Response example :
“ValueAdds”: {
“@size”: “3”,
“ValueAdd”: [
{
“@id”: “128”,
“description”: “Free Parking”
},
{
“@id”: “2048”,
“description”: “Free Wireless Internet”
},
{
“@id”: “16777216”,
“description”: “Breakfast Buffet”
}
]
}
and sometimes….
“ValueAdds”: {
“@size”: “1”,
“ValueAdd”: {
“@id”: “16777216”,
“description”: “Breakfast Buffet”
}
}
public class ValueAdds {
@JsonProperty(“@size”)
private String Size;
@JsonProperty(“ValueAdd”)
private List ValueAdd = new ArrayList();
//getters and setters
}
and my pojo expecting List of “ValueAdd”.. so getting error like “Can not deserialize instance of java.util.ArrayList out of START_OBJECT token”
Please help me on this..
Thanks in Advance…!!!
Lokesh Gupta
I will say, it’s known behavior. When there is only one object in list, jackson creates only an object; ignoring the fact that it is inside list. In other words, You’re trying to parse a JSON OBJECT “{ … }” as a JSON ARRAY “[ … ]”. To solve this issue, use ObjectMapper.configure( DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true );
Manish
Thanks Lokesh,
Issue has been Resolved.
Vikas
How we can convert below to Java object:
{
“options”: [
{
“text”: “111”,
“label”: “ABC”
},
{
“text”: “222”,
“label”: “DEF”
},
{
“text”: “333”,
“label”: “GHI”
}
]
}
Manish
Hi Vikas,
You should create one more class as options containing text and label as String..
and here options seems to be json array…so for that you need to create List of options in class where your jsonarray resides.. like..
“Employee” :
{
“options”: [
{………………………………………
you have create List list; in class Employee.
Hope this helps.
Ragunath
Hi Lokesh,
I could not find the JACKSON latest jar file t execute the above sample code. I am using the ANT project type.
Can you please share the jar file link to download?
Lokesh Gupta
It has link for downloading jar file also.
https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl/1.9.13
test
I’m getting wired error and unable to get solution for that. Could you please help?
org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON:
Can not deserialize instance of java.lang.String out of START_OBJECT token
Refat
Hi, the above example reads only one object……how to make it read more than one object….may be a silly question……please help!!!
Lokesh Gupta
There can be only one root element. So you will have to create composite object having association of all different objects you want to read/write.
Vijay
Hey Lokesh,
Suppose I have list of java objects say List and I want to convert it to json so that I can later pass it as ajax response. How can we achieve this.
In above example we are writing java object directly to file instead of that I want to hold it.
Please reply.
Lokesh Gupta
See this example to understand how we can send it to the response of a web API.
nitin
please make the source code availiable
Kamlesh Kumar
for date its not getting serialised properly.
HIMANSU NAYAK
Hi Pankaj,
Employee constructor is not using date value for initialization in employee.java.
public Employee(Integer id, String firstName, String lastName, Date birthDate){
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
sakura
That such the great article.
Anyway, if I want to write more one object at once is it possible to do that? And how?
HIMANSU NAYAK
Hi Pankaj,
defaultPrettyPrintingWriter() is deprecated api, i am using writerWithDefaultPrettyPrinter() instead.
Lokesh Gupta
Oops !! I missed it. Updated the post.
devaki
how to run the code? Is it a normal java run or maven build?
Lokesh Gupta
JavaToJSONExample.java has main() method.