杰瑞科技汇

Java JSON转对象,如何高效实现?

Of course! Converting JSON to Java objects (a process called deserialization) is a fundamental task in modern Java development. The most popular and recommended library for this is Jackson.

Java JSON转对象,如何高效实现?-图1
(图片来源网络,侵删)

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


The Recommended Method: Jackson

Jackson is the de-facto standard for JSON processing in the Java ecosystem. It's powerful, fast, and feature-rich.

Step 1: Add the Jackson Dependency

You need to add the jackson-databind library to your project. This library is usually available in your build tool's repository.

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>

Gradle (build.gradle):

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

Step 2: Create a Java Class (POJO)

Your Java class must match the structure of your JSON. The field names should match the JSON keys, and you should have a no-argument constructor.

Example JSON (user.json):

{
  "name": "John Doe",
  "email": "john.doe@example.com",
  "age": 30,
  "isStudent": false,
  "address": {
    "street": "123 Main St",
    "city": "Anytown"
  }
}

Corresponding Java Class (User.java):

Java JSON转对象,如何高效实现?-图3
(图片来源网络,侵删)
import com.fasterxml.jackson.annotation.JsonProperty; // Optional, for mapping different names
public class User {
    private String name;
    private String email;
    private int age;
    private boolean isStudent;
    // Nested object
    private Address address;
    // A no-argument constructor is required by Jackson
    public User() {
    }
    // Getters and Setters for all fields
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
    public boolean isStudent() { return isStudent; } // Note: 'is' prefix for boolean getters
    public void setStudent(boolean student) { isStudent = student; }
    public Address getAddress() { return address; }
    public void setAddress(Address address) { this.address = address; }
    // Optional: toString() for easy printing
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                ", isStudent=" + isStudent +
                ", address=" + address +
                '}';
    }
}
// Nested class for the address
class Address {
    private String street;
    private String city;
    public Address() {}
    public String getStreet() { return street; }
    public void setStreet(String street) { this.street = street; }
    public String getCity() { return city; }
    public void setCity(String city) { this.city = city; }
    @Override
    public String toString() {
        return "Address{" +
                "street='" + street + '\'' +
                ", city='" + city + '\'' +
                '}';
    }
}

Step 3: Perform the Conversion

Use ObjectMapper to read the JSON string or file and convert it into a User object.

Example: From a JSON String

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
    public static void main(String[] args) {
        // 1. Create an ObjectMapper instance
        ObjectMapper objectMapper = new ObjectMapper();
        // 2. Your JSON string
        String jsonString = """
                {
                  "name": "Jane Doe",
                  "email": "jane.doe@example.com",
                  "age": 28,
                  "isStudent": false,
                  "address": {
                    "street": "456 Oak Ave",
                    "city": "Otherville"
                  }
                }
                """;
        try {
            // 3. Use readValue() to convert JSON string to a User object
            User user = objectMapper.readValue(jsonString, User.class);
            // 4. Use the object
            System.out.println("User Name: " + user.getName());
            System.out.println("User City: " + user.getAddress().getCity());
            System.out.println("---------------------------------");
            System.out.println(user); // Uses the toString() method
        } catch (JsonProcessingException e) {
            System.err.println("Error parsing JSON: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

Example: From a JSON File If you have a file named user.json in your project's resources folder:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
public class Main {
    public static void main(String[] args) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // Read from a file
            User userFromFile = objectMapper.readValue(new File("path/to/your/user.json"), User.class);
            System.out.println("User from file: " + userFromFile);
        } catch (IOException e) {
            System.err.println("Error reading file or parsing JSON: " + e.getMessage());
        }
    }
}

Handling Complex Scenarios with Jackson

a) JSON Key to Java Field Name Mismatch

If your JSON key is user-name but your Java field is userName, use @JsonProperty.

public class User {
    @JsonProperty("user-name")
    private String userName; // Maps to "user-name" in JSON
    // ... rest of the class
}

b) Ignoring Unknown Properties

If your JSON has extra fields not present in your Java class, Jackson will throw an exception. To ignore them, use @JsonIgnoreProperties.

@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
    // ... fields ...
}

c) Deserializing to a List or Map

You can also convert JSON directly to a collection. You need to use TypeReference for generic types like List.

Example JSON (array of users):

[
  {"name": "John", "age": 30},
  {"name": "Anna", "age": 25}
]

Java Code:

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
public class Main {
    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonArrayString = """
                [
                  {"name": "John", "age": 30},
                  {"name": "Anna", "age": 25}
                ]
                """;
        // Use TypeReference to specify the generic type
        List<User> userList = objectMapper.readValue(jsonArrayString, new TypeReference<List<User>>() {});
        userList.forEach(System.out::println);
    }
}

Alternative Libraries

While Jackson is the standard, other libraries are also popular.

a) Gson (from Google)

Gson is another excellent, easy-to-use library. It's very similar in concept to Jackson.

Dependency:

<!-- Maven -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version>
</dependency>

Conversion: The code is almost identical, you just use Gson instead of ObjectMapper.

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class Main {
    public static void main(String[] args) {
        Gson gson = new Gson();
        String jsonString = "{\"name\":\"John\",\"age\":30}";
        // Convert to a single object
        User user = gson.fromJson(jsonString, User.class);
        System.out.println("User: " + user.getName());
        // Convert to a List
        String jsonArrayString = "[{\"name\":\"John\",\"age\":30},{\"name\":\"Anna\",\"age\":25}]";
        List<User> userList = gson.fromJson(jsonArrayString, new TypeToken<List<User>>() {}.getType());
        userList.forEach(u -> System.out.println("List User: " + u.getName()));
    }
}

b) org.json (A Simple Library)

This is a very lightweight library for basic JSON manipulation. It's less of a full serializer/deserializer and more of a parser.

Dependency:

<!-- Maven -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20251013</version>
</dependency>

Conversion: This approach is more manual. You parse the JSON and then manually create your Java object.

import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class Main {
    public static void main(String[] args) {
分享:
扫描分享到社交APP
上一篇
下一篇