杰瑞科技汇

Java如何将JSON转换为对象?

Of course! Converting JSON to a Java object is a very common task in modern Java development. The most popular and standard way to do this is using a library called Jackson.

Java如何将JSON转换为对象?-图1
(图片来源网络,侵删)

Here’s a complete guide, from the simplest case to more advanced scenarios.

The Short Answer (TL;DR)

To convert a JSON string to a Java object using the most popular library, Jackson, you do this:

  1. Add the Jackson dependency to your project (e.g., in pom.xml for Maven).
  2. Create a Java class that matches the structure of your JSON (the "POJO" - Plain Old Java Object).
  3. Use ObjectMapper to read the JSON string and create an instance of your Java class.
// 1. Add the dependency (Maven example)
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version> <!-- Use the latest version -->
</dependency>
// 2. Create a POJO that matches the JSON
class User {
    private String name;
    private int age;
    private String email;
    // 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 getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
    // A no-arg constructor is also a good practice
    public User() {}
}
// 3. The conversion code
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
    public static void main(String[] args) {
        String json = "{\"name\":\"Alice\",\"age\":30,\"email\":\"alice@example.com\"}";
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // The magic happens here!
            User user = objectMapper.readValue(json, User.class);
            // Now you can use the 'user' object as a regular Java object
            System.out.println("Name: " + user.getName());
            System.out.println("Age: " + user.getAge());
            System.out.println("Email: " + user.getEmail());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Detailed Explanation

Why Use a Library? (Parsing JSON Manually)

You could parse JSON manually using String manipulation or regular expressions, but it's a terrible idea.

  • Error-Prone: You'll have to handle edge cases like missing fields, different data types, and malformed JSON yourself.
  • Verbose and Slow: The code becomes long and hard to read.
  • Not Scalable: It becomes impossible to manage as your JSON structure grows.

Libraries like Jackson, Gson, and org.json handle all of this for you, safely and efficiently.

Java如何将JSON转换为对象?-图2
(图片来源网络,侵删)

The Key Players

Library Pros Cons When to Use
Jackson Industry standard, very fast, feature-rich (annotations, streaming API), integrates with Spring Boot by default. Can be complex for very simple tasks. Recommended for most projects, especially Spring Boot.
Gson Easy to use, good Google documentation, focuses on simple object mapping. Slightly slower than Jackson, fewer advanced features. A great alternative, especially if you're not in a Spring ecosystem.
org.json Very lightweight, simple API. Less flexible, less powerful than Jackson/Gson. Quick and simple tasks where you don't need full object mapping.

This guide will focus primarily on Jackson as it's the most common and powerful choice.

Step-by-Step Guide with Jackson

Step 1: Add the Jackson Dependency

You need to add jackson-databind to your build file.

Maven (pom.xml):

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

Gradle (build.gradle):

Java如何将JSON转换为对象?-图3
(图片来源网络,侵删)
implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2' // Check for the latest version

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

This is the most important step. The fields in your Java class must correspond to the keys in your JSON string.

  • Field Names: By default, Jackson maps JSON keys (e.g., "user_name") to Java fields (e.g., userName) using a standard naming convention. It's case-insensitive and ignores underscores, hyphens, etc. You can control this with annotations.
  • Getters and Setters: Jackson uses the public getters and setters to access and set the values. You must provide them.
  • No-Arg Constructor: Jackson requires a no-argument constructor to create an instance of your object before populating it. Most modern IDEs can generate this for you automatically.

Example JSON:

{
  "productId": "P12345",
  "name": "Wireless Mouse",
  "price": 25.99,
  "inStock": true
}

Corresponding Java POJO:

import com.fasterxml.jackson.annotation.JsonProperty; // Useful for explicit mapping
public class Product {
    // Private fields
    private String productId;
    private String name;
    private double price;
    private boolean inStock;
    // No-arg constructor (required by Jackson)
    public Product() {
    }
    // Getters and Setters (required by Jackson)
    public String getProductId() {
        return productId;
    }
    public void setProductId(String productId) {
        this.productId = productId;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public boolean isInStock() {
        return inStock;
    }
    public void setInStock(boolean inStock) {
        this.inStock = inStock;
    }
    // Optional: Override toString() for easy printing
    @Override
    public String toString() {
        return "Product{" +
                "productId='" + productId + '\'' +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", inStock=" + inStock +
                '}';
    }
}

Step 3: Perform the Conversion with ObjectMapper

The ObjectMapper is the main class in Jackson that handles reading and writing JSON.

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonToObjectConverter {
    public static void main(String[] args) {
        // 1. Your JSON string
        String productJson = "{\"productId\":\"P12345\",\"name\":\"Wireless Mouse\",\"price\":25.99,\"inStock\":true}";
        // 2. Create an instance of ObjectMapper
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 3. The core method: readValue
            // It takes the JSON string and the target Java class.
            Product product = objectMapper.readValue(productJson, Product.class);
            // 4. Use the Java object
            System.out.println("--- Product Details ---");
            System.out.println("ID: " + product.getProductId());
            System.out.println("Name: " + product.getName());
            System.out.println("Price: $" + product.getPrice());
            System.out.println("In Stock: " + product.isInStock());
            // Using the toString() method we created
            System.out.println("\n--- Using toString() ---");
            System.out.println(product);
        } catch (JsonProcessingException e) {
            System.err.println("Failed to parse JSON: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

Handling Complex JSON Structures

Real-world JSON is often more complex.

A. Nested Objects

JSON:

{
  "orderId": "ORD-98765",
  "customer": {
    "name": "Bob Builder",
    "email": "bob@example.com"
  },
  "totalAmount": 150.75
}

Java POJO: You need a Customer class and a reference to it in the Order class.

// Customer.java
public class Customer {
    private String name;
    private String email;
    // Getters, Setters, Constructor...
}
// Order.java
public class Order {
    private String orderId;
    private Customer customer; // Nested object
    private double totalAmount;
    // Getters, Setters, Constructor...
}

Conversion: The code is exactly the same! Jackson is smart enough to handle the nesting. Order order = objectMapper.readValue(orderJson, Order.class);

B. JSON Arrays

JSON:

[
  {"id": 1, "task": "Learn Java"},
  {"id": 2, "task": "Build an app
分享:
扫描分享到社交APP
上一篇
下一篇