杰瑞科技汇

Java JSON如何转List?

Of course! Converting a JSON string to a Java List is a very common task. The most popular and robust way to do this in Java is by using a library like Jackson, Gson, or org.json.

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

Here’s a complete guide covering the most common scenarios, from simple lists to complex lists of objects, using the recommended Jackson library.

The Scenario: JSON to a List of Objects

This is the most frequent use case. Let's assume you have a JSON array representing a list of User objects.

JSON String (users.json):

[
  {
    "id": 1,
    "name": "Alice",
    "email": "alice@example.com"
  },
  {
    "id": 2,
    "name": "Bob",
    "email": "bob@example.com"
  },
  {
    "id": 3,
    "name": "Charlie",
    "email": "charlie@example.com"
  }
]

Our Java POJO (Plain Old Java Object): This class must match the structure of the JSON objects.

Java JSON如何转List?-图2
(图片来源网络,侵删)
// User.java
public class User {
    private int id;
    private String name;
    private String email;
    // Jackson requires a no-arg constructor for deserialization
    public User() {
    }
    // Getters and Setters (can also use public fields, but getters/setters are standard)
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }
    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; }
    // Optional: A toString() method for easy printing
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

Method 1: Using Jackson (Recommended)

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

Step 1: Add Jackson Dependency

You need to include the Jackson Databind library in your project.

Maven (pom.xml):

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version> <!-- Use the latest version -->
</dependency>

Gradle (build.gradle):

Java JSON如何转List?-图3
(图片来源网络,侵删)
implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2' // Use the latest version

Step 2: Write the Conversion Code

Jackson's ObjectMapper class is the main entry point for reading and writing JSON.

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.List;
public class JsonToListConverter {
    public static void main(String[] args) {
        // 1. Your JSON String
        String jsonString = """
                [
                  {
                    "id": 1,
                    "name": "Alice",
                    "email": "alice@example.com"
                  },
                  {
                    "id": 2,
                    "name": "Bob",
                    "email": "bob@example.com"
                  },
                  {
                    "id": 3,
                    "name": "Charlie",
                    "email": "charlie@example.com"
                  }
                ]
                """;
        // 2. Create an ObjectMapper instance
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 3. Use readValue with a TypeReference
            // This is the key part! It tells Jackson to map to a List<User>.
            List<User> userList = objectMapper.readValue(jsonString, new TypeReference<List<User>>() {});
            // 4. Print the result to verify
            System.out.println("Successfully converted JSON to List<User>");
            userList.forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Why new TypeReference<List<User>>() {}?

This is a crucial concept in Jackson. When you call objectMapper.readValue(jsonString, List.class), Jackson doesn't know what type of objects are inside the List. It will default to mapping to a List of LinkedHashMap.

By using new TypeReference<List<User>>() {}, you are providing the generic type information at runtime, allowing Jackson to correctly deserialize each JSON object into a User instance.


Method 2: Using Gson

Gson is another excellent library from Google, very similar in usage to Jackson.

Step 1: Add Gson Dependency

Maven (pom.xml):

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

Gradle (build.gradle):

implementation 'com.google.code.gson:gson:2.10.1' // Use the latest version

Step 2: Write the Conversion Code

Gson's Gson class is the equivalent of Jackson's ObjectMapper.

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
public class JsonToListConverterGson {
    public static void main(String[] args) {
        // 1. Your JSON String
        String jsonString = """
                [
                  {
                    "id": 1,
                    "name": "Alice",
                    "email": "alice@example.com"
                  },
                  {
                    "id": 2,
                    "name": "Bob",
                    "email": "bob@example.com"
                  },
                  {
                    "id": 3,
                    "name": "Charlie",
                    "email": "charlie@example.com"
                  }
                ]
                """;
        // 2. Create a Gson instance
        Gson gson = new Gson();
        // 3. Use getAdapter with a TypeToken
        // This is Gson's equivalent of Jackson's TypeReference.
        Type userListType = new TypeToken<List<User>>() {}.getType();
        List<User> userList = gson.fromJson(jsonString, userListType);
        // 4. Print the result to verify
        System.out.println("Successfully converted JSON to List<User> using Gson");
        userList.forEach(System.out::println);
    }
}

Note: You'll need the same User.java class as defined above.


Method 3: Using org.json (Simpler, but less powerful)

The org.json library is simpler and doesn't require POJOs. It directly maps JSON to its own JSONObject and JSONArray types. This is useful for quick and dirty parsing or when you don't want to create Java classes.

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>

Step 2: Write the Conversion Code

This approach is different. You get a JSONArray and then iterate over it to create your List<User>.

import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class JsonToListConverterOrgJson {
    public static void main(String[] args) {
        // 1. Your JSON String
        String jsonString = """
                [
                  {
                    "id": 1,
                    "name": "Alice",
                    "email": "alice@example.com"
                  },
                  {
                    "id": 2,
                    "name": "Bob",
                    "email": "bob@example.com"
                  },
                  {
                    "id": 3,
                    "name": "Charlie",
                    "email": "charlie@example.com"
                  }
                ]
                """;
        // 2. Create a JSONArray from the string
        JSONArray jsonArray = new JSONArray(jsonString);
        // 3. Create an empty list to hold the User objects
        List<User> userList = new ArrayList<>();
        // 4. Iterate over the JSONArray
        for (int i = 0; i < jsonArray.length(); i++) {
            // Get each element as a JSONObject
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            // Manually create a User object and populate it
            User user = new User();
            user.setId(jsonObject.getInt("id"));
            user.setName(jsonObject.getString("name"));
            user.setEmail(jsonObject.getString("email"));
            // Add the user to the list
            userList.add(user);
        }
        // 5. Print the result to verify
        System.out.println("Successfully converted JSON to List<User> using org.json");
        userList.forEach(System.out::println);
    }
}

Summary: Which One Should You Use?

Feature Jackson Gson org.json
Ease of Use Excellent Excellent Good for simple cases
Performance Excellent (Fastest) Very Good Good
Flexibility Excellent Excellent Limited
Data Binding Excellent (to POJOs, Maps, etc.) Excellent (to POJOs, Maps, etc.) None (works with its own types)
Recommendation Highly Recommended for most applications. A great alternative, especially in Android. Good for quick parsing or avoiding POJOs.

For any serious application, Jackson is the best choice due to its performance, features, and widespread adoption.

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