杰瑞科技汇

Java如何实现JSON编码?

Of course! Encoding a Java object to a JSON string is a very common task. The most popular and standard way to do this in modern Java is by using the Jackson library.

Java如何实现JSON编码?-图1
(图片来源网络,侵删)

Here’s a complete guide, starting with the recommended approach and covering other popular libraries.


The Recommended Approach: Jackson

Jackson is the de-facto standard for JSON processing in the Java ecosystem. It's powerful, fast, and widely used in frameworks like Spring Boot.

Step 1: Add the Jackson Dependency

You need to include the Jackson Databind library in your project. The dependency varies depending on your build tool.

Using Maven (pom.xml):

Java如何实现JSON编码?-图2
(图片来源网络,侵删)
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version> <!-- Use the latest version -->
</dependency>

Using Gradle (build.gradle):

implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2' // Use the latest version

Step 2: Create a Java POJO (Plain Old Java Object)

Jackson works best by converting a Java object (with getters/setters) into JSON. It maps fields to JSON keys automatically.

// User.java
public class User {
    private String name;
    private int age;
    private String[] roles;
    private boolean active;
    // Jackson requires a no-arg constructor
    public User() {
    }
    // Constructor for easy object creation
    public User(String name, int age, String[] roles, boolean active) {
        this.name = name;
        this.age = age;
        this.roles = roles;
        this.active = active;
    }
    // Getters and Setters are crucial!
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
    public String[] getRoles() { return roles; }
    public void setRoles(String[] roles) { this.roles = roles; }
    public boolean isActive() { return active; }
    public void setActive(boolean active) { this.active = active; }
}

Step 3: Use ObjectMapper to Encode

The ObjectMapper class is the main entry point for using Jackson. It handles the conversion.

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonExample {
    public static void main(String[] args) {
        // 1. Create an instance of ObjectMapper
        ObjectMapper objectMapper = new ObjectMapper();
        // 2. Create a Java object
        User user = new User("John Doe", 30, new String[]{"Admin", "User"}, true);
        try {
            // 3. Convert the Java object to a JSON string
            // The 'writeValueAsString' method does the magic
            String jsonString = objectMapper.writeValueAsString(user);
            // 4. Print the JSON string
            System.out.println(jsonString);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}

Output:

Java如何实现JSON编码?-图3
(图片来源网络,侵删)
{"name":"John Doe","age":30,"roles":["Admin","User"],"active":true}

Other Popular Libraries

While Jackson is the most common, other libraries are also excellent choices.

A. Gson (Google's Library)

Gson is another very popular and easy-to-use library, also from Google.

Step 1: Add Gson Dependency Maven:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version> <!-- Use the latest version -->
</dependency>

Gradle: implementation 'com.google.code.gson:gson:2.10.1'

Step 2: Code Example The code is very similar, but you use Gson instead of ObjectMapper.

import com.google.gson.Gson;
public class GsonExample {
    public static void main(String[] args) {
        // 1. Create an instance of Gson
        Gson gson = new Gson();
        // 2. Create a Java object (same User class as before)
        User user = new User("Jane Doe", 28, new String[]{"Editor", "Moderator"}, false);
        // 3. Convert the Java object to a JSON string
        String jsonString = gson.toJson(user);
        // 4. Print the JSON string
        System.out.println(jsonString);
    }
}

Output:

{"name":"Jane Doe","age":28,"roles":["Editor","Moderator"],"active":false}

B. org.json (Simple Library)

This is a minimal, no-dependency library. It's great for simple tasks but can be less flexible for complex object graphs.

Step 1: Add org.json Dependency Maven:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20251013</version> <!-- Use the latest version -->
</dependency>

Gradle: implementation 'org.json:json:20251013'

Step 2: Code Example The usage is slightly different. You often build the JSON object directly from the Java object's fields.

import org.json.JSONObject;
public class OrgJsonExample {
    public static void main(String[] args) {
        // 1. Create a Java object (same User class as before)
        User user = new User("Peter Jones", 45, new String[]{"Developer"}, true);
        // 2. Create a JSONObject and populate it with the object's fields
        // You access fields directly using getter methods.
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", user.getName());
        jsonObject.put("age", user.getAge());
        jsonObject.put("roles", user.getRoles());
        jsonObject.put("active", user.isActive());
        // 3. The JSONObject can be converted to a string
        String jsonString = jsonObject.toString();
        // 4. Print the JSON string
        System.out.println(jsonString);
    }
}

Output:

{"name":"Peter Jones","age":45,"roles":["Developer"],"active":true}

Advanced Jackson Features

Jackson is powerful because of its annotations, which give you fine-grained control over the JSON output.

A. Customizing Field Names

Use @JsonProperty to change the JSON key.

public class User {
    @JsonProperty("full_name") // This will map to "full_name" in JSON
    private String name;
    // ... rest of the class
}

Output: {"full_name":"John Doe", ...}

B. Ignoring Fields

Use @JsonIgnore to exclude a field from the JSON output.

public class User {
    private String name;
    private int age;
    @JsonIgnore // This field will be ignored
    private String internalId;
    // ... rest of the class
}

Output: {"name":"John Doe","age":30, ...} (no internalId)

C. Handling null Values

Use @JsonInclude to control if fields with null values should be included.

import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL) // Only include non-null fields
public class User {
    private String name;
    private String email; // If this is null, it won't appear in the JSON
    // ...
}

If email is null, the output will be: {"name":"John Doe"}


Java's Built-in javax.json (Java EE / Jakarta EE)

If you are working in a Java EE or Jakarta EE environment, you can use the standard javax.json API. It's more verbose and less convenient than Jackson/Gson for direct object-to-JSON conversion.

Note: This requires a JSON-P implementation, like Eclipse Yasson or Apache Johnzon.

Example:

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
public class JsonpExample {
    public static void main(String[] args) {
        // 1. Create a JsonObjectBuilder
        JsonObjectBuilder builder = Json.createObjectBuilder();
        // 2. Add key-value pairs
        builder.add("name", "John Doe");
        builder.add("age", 30);
        builder.add("active", true);
        // 3. Create a nested JSON array
        builder.add("roles", Json.createArrayBuilder()
                .add("Admin")
                .add("User")
                .build());
        // 4. Build the final JsonObject
        JsonObject jsonObject = builder.build();
        // 5. Convert to a string
        String jsonString = jsonObject.toString();
        System.out.println(jsonString);
    }
}

Output:

{"name":"John Doe","age":30,"active":true,"roles":["Admin","User"]}

Summary and Recommendation

Library Pros Cons Best For
Jackson Industry standard, powerful, fast, highly configurable with annotations. Can be complex for simple needs; requires external dependency. Most Java applications, especially enterprise and Spring-based apps.
Gson Very easy to use, excellent documentation, handles complex objects well. Slightly slower than Jackson; less flexible for advanced configuration. Simplicity and ease of use, Google-centric projects.
org.json No dependencies, lightweight. Verbose for object conversion, less powerful features. Simple, one-off tasks or environments where adding a dependency is hard.
javax.json Standard API (in Java EE/Jakarta EE). Verbose, requires an implementation, less convenient than Jackson/Gson. Projects already using Java EE/Jakarta EE that want a standard API.

Final Recommendation: For any new project, use Jackson. It's the most robust, performant, and widely-supported option. If you need extreme simplicity and have no other dependencies, Gson is an excellent alternative.

分享:
扫描分享到社交APP
上一篇
下一篇