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
How to deserialize a JSON to Java object using the flexjson in Java?
Deserializing a JSON to a Java object means converting a JSON string into a Java object.
The deserialize() Method of the Flexjson Library
We will be using the Flexjson library to deserialize a JSON to a Java object in Java. The Flexjson library is a lightweight library that is used for serializing as well as deserializing Java objects to and from JSON.
A JSONDeserializer is the main class for performing deserialization of JSON to Java objects. We can deserialize a JSON string to a Java object using the deserialize(String json, Class<T> type) method of JSONDeserializer.
Syntax of deserialize() Method
The syntax of the deserialize() method is as follows:
public T deserialize(String json, Class<T> type)
To use the Flexjson library, we need to add it to our project. If you are using Maven, add this to your pom.xml file:
<dependency> <groupId>org.flexjson</groupId> <artifactId>flexjson</artifactId> <version>3.3</version> </dependency>
If you do not use Maven, you can download the jar file from here.
Steps to Deserialize a JSON to Java Object
Following are the steps to deserialize a JSON to a Java object using the Flexjson library:
- Create a Java class that matches the structure of your JSON data (with appropriate fields and getters/setters).
- Create a JSONDeserializer instance and use the
deserialize()method, specifying the target class. - Pass the JSON string to the
deserialize()method to convert it into a Java object. - Use the resulting Java object as needed in your application.
- Handle any exceptions such as parsing errors using try-catch if necessary.
Example
Following is the code to deserialize a JSON to a Java object using the Flexjson library:
import org.flexjson.*;
public class DeserializeJsonExample {
public static void main(String[] args) {
// JSON string to be deserialized
String jsonString = "{"name":"Ansh","age":23}";
// Create a JSONDeserializer object
JSONDeserializer<Person> deserializer = new JSONDeserializer<Person>();
// Deserialize the JSON string to a Person object
Person person = deserializer.deserialize(jsonString, Person.class);
// Print the deserialized Person object
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
Output
Name: Ansh Age: 23