Custom Deserialization in java JSONObject To Java Entity
Posted By : Lokesh Babu Sharma | 24-Nov-2020
Introduction
Serialization is a process to change the state of an object into a byte stream. Deserialization is the process to recreate java objects in memory from the byte stream. Regarding JSON, Serialization is a process to map java object into JSON Object and deserialization is the process to map JSON object into java object.
Let us now explore deserialization with the use of the Jackson package.
Here two types of deserialization will be discussed.
1. Standard Deserialization
2. Custom Deserializer
Standard Deserialization
Map java entity into a JSON object (or JSON string) without any customization is known as Standard Deserialization.
Let's create to java object:
public class Student { public int id; public String name; } public class Book { public int id; public String bookName; public Student student; }
Now map java object into JSON representation as given below:
{ "id": 1, "bookName": "the cursed", "student": { "id": 2, "name": "Amit" } }
using jackson's ObjectMapper class and it's method as given below:
Book book = new ObjectMapper().readValue(json, Book.class);
In this deserialization, JSON representation exactly matched with java entities. So JSON able to deserialize into java entity easily.
Custom Deserializer
If java entity's parameter and json object parameters are different or Json representation does not exactly match with java entities. On direct mapping it shows exception:
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "student_id" (class org.Test.dtos.Item), not marked as ignorable (3 known properties: "book_id", "student", "bookName"]) at [Source: java.io.StringReader@53c7a917; line: 1, column: 43] (through reference chain: org.Test.dtos.Item["student_id"])
So we need custom deserialization to map properly.
Let's consider the following JSON representation:
{ "student_id": 1, "sutdent_name":"", "book_id":2, "bookName": "the cursed", }
To map the above JSON representation into the above java entities, we use Jackson's JsonDeserializer class:
public class bookDeserializer extends JsonDeserializer<Book> { @Override public Book deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonNode node = jp.getCodec().readTree(jp); int studentId = (Integer) ((IntNode) node.get("student_id")).numberValue(); String bookName = node.get("bookName").asText(); int bookId = (Integer) ((IntNode) node.get("book_id")).numberValue(); String studentName = node.get("sutdent_name").asText(); return new Book(bookId, bookName, new Student(studentId, studentName)); } }
We need to register this custom deserializer to deserialize the JSON normally:
ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); module.addDeserializer(Book.class, new BookDeserializer()); mapper.registerModule(module);
Or we can register the deserializer directly on the class also:
@JsonDeserialize(using = BookDeserializer.class) public class Book { ... }
Now, we can deserialise JSON into Java entity using ObjectMapper class:
Book book = new ObjectMapper().readValue(json, Book.class);
Conclusion
Using custom deserialization, we can deserialise JSON into a java entity, even if they can not match exactly.
Our Java application development services provide increased flexibility and agility to implement new features and performance updates. We also have vast experience in cloud computing services and we let you seamlessly deploy your Java applications on platforms like AWS, Azure, and Google Cloud.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Lokesh Babu Sharma
Lokesh is in backend team. He Believes in smart work, He is good in programming. He loves to play with codes.He has expertise in Java.