SoFunction
Updated on 2025-04-14

Implementation method of converting jsonObject into object in Java

introduction

In modern web development, JSON (JavaScript Object Notation) is widely used as a lightweight data exchange format because of its readability and easy parsing characteristics. As one of the main languages ​​in back-end development, Java's ability to process JSON data is indispensable. This article will introduce how to convert jsonObject into Java objects in Java, mainly by using the Gson library to achieve this function.

1. Introduction to Gson

Gson is a Java library provided by Google for mapping between Java objects and JSON data. It can convert Java objects to JSON strings or JSON strings to equivalent Java objects. The Gson library is simple and easy to use, and is powerful, and supports complex nested objects.

2. Add Gson dependencies

Before using Gson, you need to add it to your project. If your project is built on Maven, you can add the following dependencies to the file:

<dependency>
    <groupId></groupId>
    <artifactId>gson</artifactId>
    <version>2.8.8</version>
</dependency>

For Gradle projects, you can​​The following dependencies are added to the file:

implementation ':gson:2.8.8'

3. Create Java Objects

Suppose we have a simple user information model that contains username, age, and email address. First, we need to define a corresponding Java class:

public class User {
    private String name;
    private int age;
    private String email;
 
    // No parameter constructor    public User() {}
 
    // Constructor with parameters    public User(String name, int age, String email) {
         = name;
         = age;
         = email;
    }
 
    // Getter and Setter methods    public String getName() {
        return name;
    }
 
    public void setName(String name) {
         = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
         = age;
    }
 
    public String getEmail() {
        return email;
    }
 
    public void setEmail(String email) {
         = email;
    }
 
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", email='" + email + '\'' +
                '}';
    }
}

4. Convert jsonObject to Java object

With the above​User​Class, we can easily convert a JSON object to using Gson​User​Object. Suppose we have the following JSON string:

{
    "name": "Zhang San",
    "age": 25,
    "email": "zhangsan@"
}

Here is how to convert this JSON string to using Gson​User​Object:

import ;
 
public class JsonToObjectExample {
    public static void main(String[] args) {
        // JSON string        String json = "{\"name\":\"Zhang San\",\"age\":25,\"email\":\"zhangsan@\"}";
 
        // Create a Gson object        Gson gson = new Gson();
 
        // Convert JSON string to User object        User user = (json, );
 
        // Output information of User object        (user);
    }
}

Run the above program and the output will be:

User{name='Zhang San', age=25, email='zhangsan@'}

This indicates that the JSON string has been successfully converted to a Java object.

In this way, JSON data can be easily processed in Java applications, especially when making network requests and responses. The powerful features of the Gson library and the concise API design make the conversion between JSON and Java objects very simple and efficient. Converting JSON objects to Java objects is a common requirement, especially when dealing with web service responses or configuration files. To achieve this, we can use some popular libraries such as Jackson, Gson, etc. Below I will use these two libraries separately to demonstrate how to convert a JSON object to a Java object.

Sample Scenario

Suppose we have a JSON string with user information, as shown below:

{
  "name": "Zhang San",
  "age": 28,
  "email": "zhangsan@"
}

Our goal is to convert this JSON string into a Java object.

Using Jackson Library

First, you need to add the Jackson library to your project. If you use Maven, you can​​Add the following dependencies:

<dependency>
    <groupId></groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.3</version>
</dependency>

Then, define a corresponding Java class (User):

public class User {
    private String name;
    private int age;
    private String email;
 
    // No parameter constructor    public User() {}
 
    // Getter and Setter methods    public String getName() {
        return name;
    }
 
    public void setName(String name) {
         = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
         = age;
    }
 
    public String getEmail() {
        return email;
    }
 
    public void setEmail(String email) {
         = email;
    }
 
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", email='" + email + '\'' +
                '}';
    }
}

Next, write code to convert the JSON string to​User​Object:

import ;
 
public class JsonToJavaObjectExample {
    public static void main(String[] args) {
        String jsonString = "{\"name\": \"Zhang San\", \"age\": 28, \"email\": \"zhangsan@\"}";
        
        try {
            ObjectMapper mapper = new ObjectMapper();
            User user = (jsonString, );
            (user);
        } catch (Exception e) {
            ();
        }
    }
}

Using the Gson library

Similarly, add the Gson library to your project first. If you use Maven, you can​​Add the following dependencies:

<dependency>
    <groupId></groupId>
    <artifactId>gson</artifactId>
    <version>2.8.9</version>
</dependency>

The code for converting using Gson is as follows:

import ;
 
public class JsonToJavaObjectExample {
    public static void main(String[] args) {
        String jsonString = "{\"name\": \"Zhang San\", \"age\": 28, \"email\": \"zhangsan@\"}";
        
        Gson gson = new Gson();
        User user = (jsonString, );
        (user);
    }
}

The above is how to convert JSON strings into Java objects using Jackson and Gson libraries. Both methods are very simple and efficient, and you can choose the right library according to the specific needs of the project. In Java, place the JSON object (​​JSONObject​​) Converting to Java objects is a common requirement, especially when handling API responses, configuration files, or data exchange formats. This can usually be achieved by using some popular libraries such as Jackson, Gson or etc.

Using Jackson Library

Jackson is a very powerful JSON processing library that supports converting JSON strings to Java objects and vice versa. Here is how to use Jackson to​JSONObject​​Example of converting to Java objects:

  1. Add dependencies: First, make sure your project contains the Jackson library. If you use Maven, you canAdd the following dependencies to:
<dependency>
    <groupId></groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.3</version>
</dependency>
  • Define Java classes: Suppose you have a simple Java classUser, it hasidandnameTwo attributes.
public class User {
    private int id;
    private String name;
 
    // No parameter constructor    public User() {}
 
    // Parameter constructor    public User(int id, String name) {
         = id;
         = name;
    }
 
    // Getter and Setter methods    public int getId() {
        return id;
    }
 
    public void setId(int id) {
         = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
         = name;
    }
 
    @Override
    public String toString() {
        return "User{" +
                ", name='" + name + '\'' +
                '}';
    }
}
  • WillJSONObjectConvert to Java object
import ;
import ;
 
public class JsonToJavaObjectExample {
    public static void main(String[] args) {
        // Create a JSONObject        JSONObject jsonObject = new JSONObject();
        ("id", 1);
        ("name", "John Doe");
 
        // Convert JSONObject to JSON string        String jsonString = ();
 
        // Convert JSON strings to Java objects using ObjectMapper        ObjectMapper objectMapper = new ObjectMapper();
        try {
            User user = (jsonString, );
            (user);
        } catch (Exception e) {
            ();
        }
    }
}

Using the Gson library

Gson is another commonly used JSON processing library developed by Google. Here is what to use Gson to​JSONObject​​Example of converting to Java objects:

  • Add dependencies: Make sure your project contains the Gson library. If you use Maven, you canAdd the following dependencies to:
<dependency>
    <groupId></groupId>
    <artifactId>gson</artifactId>
    <version>2.8.8</version>
</dependency>
  • Define Java classes: Use the same as aboveUserkind.
  • WillJSONObjectConvert to Java object
import ;
import ;
 
public class JsonToJavaObjectExample {
    public static void main(String[] args) {
        // Create a JSONObject        JSONObject jsonObject = new JSONObject();
        ("id", 1);
        ("name", "John Doe");
 
        // Convert JSONObject to JSON string        String jsonString = ();
 
        // Convert JSON strings to Java objects using Gson        Gson gson = new Gson();
        User user = (jsonString, );
        (user);
    }
}

Usage library

Although the library does not directly support it​JSONObject​Convert to Java object, but you can manually extract fields and set them into Java object. Here is an example:

  • Define Java classes: Use the same as aboveUserkind.
  • WillJSONObjectConvert to Java object
import ;
 
public class JsonToJavaObjectExample {
    public static void main(String[] args) {
        // Create a JSONObject        JSONObject jsonObject = new JSONObject();
        ("id", 1);
        ("name", "John Doe");
 
        // Manually extract fields and set them to Java objects        User user = new User();
        (("id"));
        (("name"));
 
        (user);
    }
}

The above are three common methods,​JSONObject​​Convert to Java object. Which method to choose depends on your specific needs and the libraries already used in your project. Both Jackson and Gson offer more powerful and flexible features, while simpler but limited in functionality.

This is the article about the implementation method of converting jsonObject into an object in Java. For more related contents of converting jsonObject into an object in Java, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!