📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In the world of Java programming, JSON (JavaScript Object Notation) is a widely used format for data interchange. It's common to receive JSON data from a web service or API and then deserialize it into Java objects. With the introduction of Java records in Java 16, the process of deserializing JSON data has become more streamlined and efficient. In this blog post, we'll explore how to deserialize JSON into Java records, a feature that greatly simplifies data handling in Java applications.
Introduction to Java Records
Java Records, introduced in Java 16, is a special type of data class in the Java language. They provide a concise and straightforward way to declare classes that are primarily used to hold immutable data.
Records automatically generate boilerplate code like constructors, getters, equals(), hashCode(), and toString() methods based on the fields declared. A record is defined with the record keyword, followed by a list of fields. This feature simplifies the creation of data transfer objects and value-based classes, promoting cleaner and more readable code.
Example of a Java Record:
public record User(Long id, String firstName, String lastName, String email) {}
Advantages of Using Java Records for JSON Deserialization
Setting Up the Environment
Maven Dependency for Jackson
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.16.1</version>
</dependency>
Deserializing JSON to Java Record
package net.javaguides.quizapp.automation;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
record User(Long id, String firstName, String lastName, String email) {}
public class JsonToRecord {
public static void main(String[] args) {
String json = """
{
"id": 1,
"firstName": "Ramesh",
"lastName": "Fadatare",
"email": "ramesh@example.com"
}
""";
ObjectMapper mapper = new ObjectMapper();
try {
User user = mapper.readValue(json, User.class);
System.out.println("Deserialized User Record: " + user);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
Deserialized User Record: User[id=1, firstName=Ramesh, lastName=Fadatare, email=ramesh@example.com]
Java Records for Complex Structures
Defining the Records
public record Address(String street, String city, String zipCode, String country) {}
Next, define the User record, which includes an Address:
public record User(Long id, String firstName, String lastName, String email, Address address) {}
Deserializing Nested JSON
{
"id": 1,
"firstName": "Ramesh",
"lastName": "Fadatare",
"email": "ramesh@example.com",
"address": {
"street": "Main street",
"city": "Pune",
"zipCode": "12345",
"country": "India"
}
}
The Deserialization Process
package net.javaguides.quizapp.automation;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
record Address(String street, String city, String zipCode, String country) {}
record User(Long id, String firstName, String lastName, String email, Address address) {}
public class ComplexJsonToRecord {
public static void main(String[] args) {
String json = """
{
"id": 1,
"firstName": "Ramesh",
"lastName": "Fadatare",
"email": "ramesh@example.com",
"address": {
"street": "Main street",
"city": "Pune",
"zipCode": "12345",
"country": "India"
}
}
""";
ObjectMapper mapper = new ObjectMapper();
try {
User user = mapper.readValue(json, User.class);
System.out.println("Deserialized User Record: " + user);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
Deserialized User Record: User[id=1, firstName=Ramesh, lastName=Fadatare, email=ramesh@example.com, address=Address[street=Main street, city=Pune, zipCode=12345, country=India]]
Comments
Post a Comment
Leave Comment