杰瑞科技汇

Java如何转为JSONObject?

Of course! Converting Java objects to JSONObject is a fundamental task in Java, especially when dealing with web services and APIs. The most popular and robust way to do this is by using the Jackson library.

Java如何转为JSONObject?-图1
(图片来源网络,侵删)

Here’s a comprehensive guide covering:

  1. The Recommended Method: Using Jackson
  2. A Simpler Method: Using org.json
  3. Converting a List of Objects
  4. Handling Complex Scenarios (Date, Custom Serializers)

The Recommended Method: Using Jackson

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

Step 1: Add Jackson Dependency

First, you need to include the Jackson library in your project. If you're using a build tool like Maven or Gradle, add the following dependency.

Maven (pom.xml):

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

Gradle (build.gradle):

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

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

Create a Java class that matches the structure of your desired JSON. The fields must have getters and setters (or be public).

// src/main/java/com/example/User.java
public class User {
    private String name;
    private int age;
    private String email;
    private boolean isActive;
    // No-args constructor is required by Jackson
    public User() {
    }
    public User(String name, int age, String email, boolean isActive) {
        this.name = name;
        this.age = age;
        this.email = email;
        this.isActive = isActive;
    }
    // Getters and Setters
    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 getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
    public boolean isActive() { return isActive; }
    public void setActive(boolean active) { isActive = active; }
}

Step 3: Convert the POJO to JSONObject

Jackson's ObjectMapper class handles the conversion. It directly serializes your object to a JSON string. To get a JSONObject from the org.json library, you'll parse this string.

import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONObject;
public class Main {
    public static void main(String[] args) {
        // 1. Create an instance of your POJO
        User user = new User("Alice", 30, "alice@example.com", true);
        // 2. Create Jackson's ObjectMapper
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 3. Convert Java object to JSON string
            String jsonString = objectMapper.writeValueAsString(user);
            System.out.println("JSON String from Jackson: " + jsonString);
            // 4. (Optional) Convert the JSON string to org.json.JSONObject
            JSONObject jsonObject = new JSONObject(jsonString);
            System.out.println("\norg.json.JSONObject: " + jsonObject.toString());
            // You can now access fields like this:
            System.out.println("\nUser Name from JSONObject: " + jsonObject.getString("name"));
            System.out.println("User Age from JSONObject: " + jsonObject.getInt("age"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

Java如何转为JSONObject?-图3
(图片来源网络,侵删)
JSON String from Jackson: {"name":"Alice","age":30,"email":"alice@example.com","isActive":true}
org.json.JSONObject: {"name":"Alice","age":30,"email":"alice@example.com","isActive":true}
User Name from JSONObject: Alice
User Age from JSONObject: 30

A Simpler Method: Using org.json

If you don't need the full power of Jackson and just need a quick conversion, you can use the org.json library directly. This approach is less flexible for complex objects.

Step 1: Add org.json Dependency

Maven (pom.xml):

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

Gradle (build.gradle):

implementation 'org.json:json:20251013' // Use the latest version

Step 2: Create a POJO (Same as before)

The User.java class from the previous example is perfectly fine here.

Step 3: Convert the POJO to JSONObject

You manually create the JSONObject and populate it using the getter methods of your POJO. This requires more code but doesn't rely on reflection.

import org.json.JSONObject;
import java.lang.reflect.Method;
public class MainOrgJson {
    public static void main(String[] args) {
        User user = new User("Bob", 25, "bob@example.com", false);
        // Create a new JSONObject
        JSONObject jsonObject = new JSONObject();
        // Use reflection to get all getters and populate the JSONObject
        // Note: This is a simple example and might not handle all edge cases.
        // A more robust solution would iterate over fields.
        Method[] methods = user.getClass().getMethods();
        for (Method method : methods) {
            if (method.getName().startsWith("get") && method.getParameterCount() == 0) {
                try {
                    String key = method.getName().substring(3); // Remove "get"
                    key = Character.toLowerCase(key.charAt(0)) + key.substring(1); // lowerCase first letter
                    Object value = method.invoke(user);
                    jsonObject.put(key, value);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("JSONObject created manually: " + jsonObject.toString());
    }
}

Output:

JSONObject created manually: {"name":"Bob","age":25,"email":"bob@example.com","isActive":false}

Converting a List of Objects

What if you have a List<User>? You can use Jackson to convert it to a JSON array.

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.Arrays;
import java.util.List;
public class ListToJson {
    public static void main(String[] args) {
        // 1. Create a list of User objects
        List<User> users = Arrays.asList(
            new User("Alice", 30, "alice@example.com", true),
            new User("Bob", 25, "bob@example.com", false),
            new User("Charlie", 35, "charlie@example.com", true)
        );
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 2. Convert List to JSON Array string
            String jsonArrayString = objectMapper.writeValueAsString(users);
            System.out.println("JSON Array String: " + jsonArrayString);
            // 3. Convert the JSON string to org.json.JSONArray
            JSONArray jsonArray = new JSONArray(jsonArrayString);
            System.out.println("\norg.json.JSONArray: " + jsonArray.toString());
            // Access an element in the array
            JSONObject firstUser = jsonArray.getJSONObject(0);
            System.out.println("\nFirst user's name: " + firstUser.getString("name"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

JSON Array String: [{"name":"Alice","age":30,"email":"alice@example.com","isActive":true},{"name":"Bob","age":25,"email":"bob@example.com","isActive":false},{"name":"Charlie","age":35,"email":"charlie@example.com","isActive":true}]
org.json.JSONArray: [{"name":"Alice","age":30,"email":"alice@example.com","isActive":true},{"name":"Bob","age":25,"email":"bob@example.com","isActive":false},{"name":"Charlie","age":35,"email":"charlie@example.com","isActive":true}]
First user's name: Alice

Handling Complex Scenarios

Handling Dates

By default, Jackson serializes dates to a timestamp number. You can customize this using annotations.

import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
public class Event {
    private String eventName;
    // Specify the desired date format
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
    private Date eventDate;
    // Constructor, getters, setters...
    public Event(String eventName, Date eventDate) {
        this.eventName = eventName;
        this.eventDate = eventDate;
    }
    // ... getters and setters
}

When you serialize an Event object, the eventDate will be in the specified format instead of a timestamp.

Ignoring Fields

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

public class User {
    // ... other fields
    @JsonIgnore
    private String passwordHash; // This will not appear in the JSON
    // ... other fields
}

Custom Serialization

For full control, you can create a custom serializer.

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.io.IOException;
public class User {
    private String name;
    private int secretLevel; // We want to format this specially
    // Annotate the field with the custom serializer
    @JsonSerialize(using = SecretLevelSerializer.class)
    public int getSecretLevel() {
        return secretLevel;
    }
    // ... other fields and methods
}
// Custom Serializer
class SecretLevelSerializer extends JsonSerializer<Integer> {
    @Override
    public void serialize(Integer value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        // Custom logic: prepend "LEVEL-"
        gen.writeString("LEVEL-" + value);
    }
}

When serialized, secretLevel with value 5 will appear as "LEVEL-5".

Summary: Which Method to Choose?

Method Pros Cons Best For
Jackson Industry standard, extremely powerful, handles complex objects, dates, enums, and nested structures well. Supports annotations for fine-grained control. Requires a dependency. Slight learning curve for advanced features. Almost all scenarios. Web APIs, REST clients, complex data models.
org.json Simple, no complex configuration. Good for quick, one-off conversions. Tedious for large objects (manual population). Less powerful for complex scenarios (dates, nested objects). Simple scripts, small projects, or when you absolutely cannot add a heavy dependency like Jackson.
分享:
扫描分享到社交APP
上一篇
下一篇