杰瑞科技汇

Java中string转json有哪些方法?

Of course! Converting a String to a JSON object in Java is a very common task. The best way to do this is by using a dedicated JSON library. The most popular and user-friendly ones are Jackson, Gson, and org.json.

Java中string转json有哪些方法?-图1
(图片来源网络,侵删)

Here’s a complete guide covering the most common scenarios with each library.

Scenario 1: Simple JSON String to a Java Object (POJO)

This is the most common and recommended approach. You have a JSON string that represents a structured object, and you want to convert it directly into an instance of a Java class (a POJO - Plain Old Java Object).

Step 1: Create a POJO

First, create a Java class that mirrors the structure of your JSON. The field names should match the JSON keys.

// User.java
public class User {
    private int id;
    private String name;
    private String email;
    // Getters and Setters are essential for the library to work!
    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 A: Using Jackson (Recommended)

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

Java中string转json有哪些方法?-图2
(图片来源网络,侵删)

Add Jackson Dependency

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):

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

Write the Conversion Code

Jackson uses an ObjectMapper to perform the conversion.

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonExample {
    public static void main(String[] args) {
        // The JSON string you want to convert
        String jsonString = "{\"id\": 101, \"name\": \"John Doe\", \"email\": \"john.doe@example.com\"}";
        // Create an instance of ObjectMapper
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // Use readValue() to convert the string to a User object
            User user = objectMapper.readValue(jsonString, User.class);
            // Now you have a fully populated User object
            System.out.println("Successfully converted JSON to User object:");
            System.out.println(user);
            System.out.println("User Name: " + user.getName());
            System.out.println("User Email: " + user.getEmail());
        } catch (JsonProcessingException e) {
            System.err.println("Error parsing JSON string: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

Method B: Using Gson

Gson is Google's JSON library. It's also very popular and straightforward to use.

Java中string转json有哪些方法?-图3
(图片来源网络,侵删)

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

Write the Conversion Code

Gson's Gson class is the main entry point.

import com.google.gson.Gson;
public class GsonExample {
    public static void main(String[] args) {
        // The JSON string you want to convert
        String jsonString = "{\"id\": 101, \"name\": \"John Doe\", \"email\": \"john.doe@example.com\"}";
        // Create an instance of Gson
        Gson gson = new Gson();
        // Use fromJson() to convert the string to a User object
        // The second parameter is the target class type
        User user = gson.fromJson(jsonString, User.class);
        // Now you have a fully populated User object
        System.out.println("Successfully converted JSON to User object:");
        System.out.println(user);
        System.out.println("User Name: " + user.getName());
        System.out.println("User Email: " + user.getEmail());
    }
}

Scenario 2: Simple JSON String to a Map or List

Sometimes you don't have a predefined POJO, or you're working with dynamic data. In this case, you can convert the JSON string into a Map<String, Object> or a List<Object>.

Using Jackson

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
import java.util.Map;
public class JacksonDynamicExample {
    public static void main(String[] args) throws Exception {
        String jsonString = "{\"id\": 101, \"name\": \"John Doe\", \"hobbies\": [\"reading\", \"coding\"]}";
        ObjectMapper objectMapper = new ObjectMapper();
        // Convert to a Map
        // TypeReference is needed to specify the generic type of the Map
        Map<String, Object> dataMap = objectMapper.readValue(jsonString, new TypeReference<Map<String, Object>>() {});
        System.out.println("Converted to Map:");
        System.out.println(dataMap);
        System.out.println("Name from Map: " + dataMap.get("name"));
        // Convert a JSON array string to a List
        String jsonArrayString = "[\"apple\", \"banana\", \"cherry\"]";
        List<String> fruitList = objectMapper.readValue(jsonArrayString, new TypeReference<List<String>>() {});
        System.out.println("\nConverted to List:");
        System.out.println(fruitList);
    }
}

Using Gson

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
public class GsonDynamicExample {
    public static void main(String[] args) {
        String jsonString = "{\"id\": 101, \"name\": \"John Doe\", \"hobbies\": [\"reading\", \"coding\"]}";
        Gson gson = new Gson();
        // Convert to a Map
        // TypeToken is needed to specify the generic type of the Map
        Type mapType = new TypeToken<Map<String, Object>>() {}.getType();
        Map<String, Object> dataMap = gson.fromJson(jsonString, mapType);
        System.out.println("Converted to Map:");
        System.out.println(dataMap);
        System.out.println("Name from Map: " + dataMap.get("name"));
        // Convert a JSON array string to a List
        String jsonArrayString = "[\"apple\", \"banana\", \"cherry\"]";
        Type listType = new TypeToken<List<String>>() {}.getType();
        List<String> fruitList = gson.fromJson(jsonArrayString, listType);
        System.out.println("\nConverted to List:");
        System.out.println(fruitList);
    }
}

Scenario 3: Malformed JSON String

What happens if your JSON string is invalid? Both libraries will throw an exception. It's crucial to handle this gracefully.

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ErrorHandlingExample {
    public static void main(String[] args) {
        String badJsonString = "{\"id\": 101, \"name\": \"John Doe\", \"email\": \"john.doe@example.com\""; // Missing closing brace
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            User user = objectMapper.readValue(badJsonString, User.class);
            System.out.println(user);
        } catch (JsonProcessingException e) {
            // This block will catch the parsing error
            System.err.println("Failed to parse JSON. It might be malformed.");
            System.err.println("Error details: " + e.getMessage());
        }
    }
}

Summary and Recommendation

Feature Jackson Gson org.json
Ease of Use Very easy Very easy Easy, but less flexible
Performance Excellent (Fastest) Very Good Good
Features Excellent (Streaming API, Tree Model, Data Binding) Good (Data Binding, Streaming) Basic (Data Binding only)
Ecosystem Industry Standard (Used by Spring, etc.) Widely Used Lightweight
Dependency jackson-databind gson org.json

Recommendation:

  • For any new project, especially if you're using the Spring ecosystem, use Jackson. It's the most powerful, performant, and widely adopted library.
  • **If you need a simple, no-frills library and don't want any external dependencies beyond the core, Gson is an
分享:
扫描分享到社交APP
上一篇
下一篇