Java Object to JSON String

How to convert a Java object to a JSON string in Java?

Converting a Java object to a JSON string should be relatively simple. This article is mainly for reviewing and summarizing different ways to convert Java objects to JSON strings.

Here, let's start with the first method, using the Jackson library for conversion.

Using the Jackson library

Example code:


import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
    public static void main(String[] args) {
        User user = new User();
        user.setFirstName("John");
        user.setLastName("Doe");
        user.setEmail("hello@json2.top");

        ObjectMapper mapper = new ObjectMapper();
        try {
            String json = mapper.writeValueAsString(user);
            System.out.println(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
        

The above is the usage of the Jackson library for converting JSON strings, which is quite simple. The Jackson library has encapsulated the process, and you only need to pass in your Java object model, leaving the rest to the Jackson library to handle. There's no need to focus on the specific parsing details, allowing developers to focus more on the specific business logic.

In addition to the Jackson library, let's look at another alternative.

Using the Gson library

The usage of the Gson library is similar to the Jackson library. You pass in the object model, and Gson library handles the rest of the logic. Let's take a look at the code.

Example code:


import com.google.gson.Gson;

public class Main {
    public static void main(String[] args) {
        User user = new User();
        user.setFirstName("John");
        user.setLastName("Doe");
        user.setEmail("hello@json2.top");

        Gson gson = new Gson();
        String json = gson.toJson(user);
        System.out.println(json);
    }
}
        

In addition to the Gson and Jackson libraries, I also want to use the native JSONObject to parse into a JSON string. The usage is simple, but it becomes complicated if you want to convert it back to a Java object from a string.

Native JSONObject

Example code:


import org.json.JSONObject;

public class Main {
    public static void main(String[] args) {
        User user = new User();
        user.setFirstName("John");
        user.setLastName("Doe");
        user.setEmail("hello@json2.top");

        JSONObject jsonObject = new JSONObject(user);
        String jsonString = jsonObject.toString();
        System.out.println(jsonString);
    }
}
        

In the previous article, we discussed how to parse a string into a Java object, but we did not introduce the method using the native JSONObject. Here's an example code snippet.

Example code:

import org.json.JSONObject;

public class Main {
    public static void main(String[] args) {
        String json = "{\"firstName\":\"John\",\"lastName\":\"Doe\",\"email\":\"hello@json2.top\"}";

        JSONObject jsonObject = new JSONObject(json);
        String firstName = jsonObject.getString("firstName");
        String lastName = jsonObject.getString("lastName");
        String email = jsonObject.getString("email");

        System.out.println("First Name: " + firstName);
        System.out.println("Last Name: " + lastName);
        System.out.println("Email: " + email);
    }
}

Additional notes:

Maven dependency for Jackson library:

<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.5</version>
        </dependency>

Gradle dependency for Jackson library:

implementation 'com.fasterxml.jackson.core:jackson-databind:2.12.5'

Maven dependency for Gson library:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.8</version>
</dependency>

Gradle dependency for Gson library:

implementation 'com.google.code.gson:gson:2.8.8'

Maven dependency for org.json.JSONObject:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20180813</version>
</dependency>

Gradle dependency for org.json.JSONObject:

implementation 'org.json:json:20180813'

It is important to note that in Android projects, Google already includes org.json.JSONObject in the SDK by default, so we do not need to add the dependency separately. However, in Java projects, it is still necessary to manually add the remote dependency.

That's the content of this article, mainly introducing several common methods for converting Java objects to JSON strings. You can bookmark this article for easy reference.

Relative Articles

Why JSON preferred over XML?    Optimizing Efficiency: Best Practices for JSON Compression     Mastering JSON Compression: Techniques, Tools, and Performance Optimization     Java String to JSON Object