杰瑞科技汇

java jackson json

Of course! Here is a comprehensive guide to using the Jackson library for JSON processing in Java, covering the most common use cases from basic serialization to advanced features.

java jackson json-图1
(图片来源网络,侵删)

What is Jackson?

Jackson is a popular, high-performance Java library for processing JSON data. It's widely used in the Java ecosystem and is the default JSON processor for many frameworks, including Spring Boot.

Jackson provides three main modules:

  1. jackson-databind: The core module. It provides the "data binding" functionality, which allows you to convert JSON to and from Java objects (POJOs) and JSON trees. This is the module you'll use 99% of the time.
  2. jackson-core: The streaming API (low-level). It provides a pull parser and a generator for reading and writing JSON as a stream of tokens. It's very fast and memory-efficient but requires more code.
  3. jackson-annotations: Contains annotations that you can use on your Java classes to control the serialization and deserialization process.

Setup (Maven)

First, you need to add the Jackson dependencies to your project. For most use cases, you only need databind.

<dependencies>
    <!-- The core databind module, which depends on core and annotations -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.17.0</version> <!-- Use the latest version -->
    </dependency>
</dependencies>

Serialization: Java Object to JSON

This is the process of converting a Java object into a JSON string.

java jackson json-图2
(图片来源网络,侵删)

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

Your Java class needs to have fields (with getters and setters) that match the keys in your JSON.

// src/main/java/com/example/User.java
package com.example;
public class User {
    private String name;
    private int age;
    private String[] roles;
    // Jackson requires a no-arg constructor
    public User() {
    }
    public User(String name, int age, String[] roles) {
        this.name = name;
        this.age = age;
        this.roles = roles;
    }
    // Getters and Setters are essential!
    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[] getRoles() { return roles; }
    public void setRoles(String[] roles) { this.roles = roles; }
    // Optional: Override toString() for easy printing
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", roles=" + String.join(", ", roles) +
                '}';
    }
}

Step 2: Use ObjectMapper

The ObjectMapper is the central class in Jackson for performing data binding.

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.example.User;
public class Main {
    public static void main(String[] args) {
        // 1. Create an instance of ObjectMapper
        ObjectMapper objectMapper = new ObjectMapper();
        // 2. Create a Java object
        User user = new User("Alice", 30, new String[]{"admin", "user"});
        try {
            // 3. Serialize the object to a JSON string
            // The 'writeValueAsString' method is very convenient
            String jsonString = objectMapper.writeValueAsString(user);
            System.out.println("Serialized JSON:");
            System.out.println(jsonString);
            // You can also write to a file or an output stream
            // objectMapper.writeValue(new File("user.json"), user);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}

Output:

{"name":"Alice","age":30,"roles":["admin","user"]}

Deserialization: JSON to Java Object

This is the reverse process: converting a JSON string back into a Java object.

java jackson json-图3
(图片来源网络,侵删)
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.example.User;
public class Main {
    public static void main(String[] args) {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = "{\"name\":\"Bob\",\"age\":25,\"roles\":[\"editor\",\"guest\"]}";
        try {
            // 1. Deserialize the JSON string to a User object
            User user = objectMapper.readValue(jsonString, User.class);
            // 2. Use the object
            System.out.println("Deserialized Object:");
            System.out.println(user); // Uses the toString() method
            System.out.println("User's name: " + user.getName());
            System.out.println("User's first role: " + user.getRoles()[0]);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}

Output:

Deserialized Object:
User{name='Bob', age=25, roles=editor, guest}
User's name: Bob
User's first role: editor

Handling JSON Arrays

To deserialize a JSON array (e.g., [...]), you need to use List.class or User[].class. However, Jackson needs to know the specific type of the list elements. You can use TypeReference for this.

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.example.User;
import java.util.List;
public class Main {
    public static void main(String[] args) {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonArrayString = "[" +
                "{\"name\":\"Alice\",\"age\":30,\"roles\":[\"admin\"]}," +
                "{\"name\":\"Bob\",\"age\":25,\"roles\":[\"editor\"]}" +
                "]";
        try {
            // Use TypeReference to specify the generic type List<User>
            List<User> userList = objectMapper.readValue(jsonArrayString, new TypeReference<List<User>>() {});
            System.out.println("Deserialized List of Users:");
            userList.forEach(System.out::println);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}

Output:

Deserialized List of Users:
User{name='Alice', age=30, roles=admin}
User{name='Bob', age=25, roles=editor}

Common Annotations

Annotations give you fine-grained control over how your objects are serialized and deserialized.

Annotation Use Case Example
@JsonProperty Map a field to a different JSON key name. @JsonProperty("user_name") private String name;
@JsonIgnore Exclude a field entirely from the JSON output. @JsonIgnore private String internalId;
@JsonIgnoreProperties Ignore unknown properties in the JSON during deserialization. @JsonIgnoreProperties(ignoreUnknown = true) on the class.
@JsonFormat Format a date/time field. @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") private Date birthDate;
@JsonCreator Customize the constructor/factory method used for deserialization (useful for immutable objects). @JsonCreator public User(@JsonProperty("n") String name) { ... }
@JsonInclude Include or exclude fields based on their value (e.g., NON_NULL). @JsonInclude(JsonInclude.Include.NON_NULL) on the class or field.

Example with Annotations

import com.fasterxml.jackson.annotation.*;
@JsonInclude(JsonInclude.Include.NON_NULL) // Don't include null fields in JSON
public class Product {
    @JsonProperty("prod_name") // Maps "prod_name" in JSON to the 'name' field
    private String name;
    private double price;
    @JsonIgnore // This field will never appear in JSON
    private String internalSku;
    // Constructor for creating objects
    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }
    // Getters and Setters...
    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 String getInternalSku() { return internalSku; }
    public void setInternalSku(String internalSku) { this.internalSku = internalSku; }
}

Serialization:

Product p = new Product("Laptop", 1200.50);
p.setInternalSku("SKU-12345"); // This will be ignored
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(p));

Output:

{"prod_name":"Laptop","price":1205}

Tree Model (JSON as a Java Tree)

Sometimes you don't have a predefined Java class. The Tree Model lets you manipulate JSON as a tree of JsonNode objects, which is very flexible.

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
public class TreeModelExample {
    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        // 1. Parse a JSON string into a JsonNode tree
        String jsonString = "{\"name\":\"Charlie\",\"age\":40,\"city\":\"New York\"}";
        JsonNode rootNode = mapper.readTree(jsonString);
        // 2. Navigate the tree
        String name = rootNode.get("name").asText();
        int age = rootNode.get("age").asInt();
        System.out.println("Name: " + name + ", Age: " + age);
        // 3. Modify the tree
        ((ObjectNode) rootNode).put("city", "San Francisco");
        rootNode.put("country", "USA");
        // 4. Convert the tree back to a JSON string
        String modifiedJson = mapper.writeValueAsString(rootNode);
        System.out.println("\nModified JSON:");
        System.out.println(modifiedJson);
    }
}

Output:

Name: Charlie, Age: 40
Modified JSON:
{"name":"Charlie","age":40,"city":"San Francisco","country":"USA"}

Summary

Task Method / Key Concept Description
Serialize objectMapper.writeValueAsString(object) Converts a Java object to a JSON string.
Deserialize objectMapper.readValue(jsonString, MyClass.class) Converts a JSON string to a Java object.
Handle Arrays objectMapper.readValue(jsonArray, new TypeReference<List<MyClass>>() {}) Converts a JSON array to a List of objects.
Control Mapping @JsonProperty, @JsonIgnore, etc. Annotate POJO fields to customize JSON mapping.
Flexible Parsing JsonNode Tree Model Parse and manipulate JSON without a predefined class.
Core Class ObjectMapper The main entry point for all data binding operations.
分享:
扫描分享到社交APP
上一篇
下一篇