Overview

JsonUtils is a core utility class for JSON serialization and deserialization, implemented using the Jackson library. Its main functionality is bidirectional conversion between Java objects and JSON strings, used in API communication for serializing request parameters and deserializing response data.

Code Examples

import com.fasterxml.jackson.databind.ObjectMapper;
import java.nio.charset.StandardCharsets;

/**
 * JSON serialization/deserialization utility class
 * <p>
 * Provides conversion between Java objects and JSON strings,
 * using the Jackson library for efficient and stable serialization operations.
 */
public class JsonUtils {
    // Globally shared ObjectMapper instance
    private static final ObjectMapper mapper = new ObjectMapper();

    static {
        // Configure to ignore unknown fields
        mapper.configure(
            com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
            false
        );
    }

    /**
     * Serialize object to JSON string
     *
     * @param object Java object to be serialized
     * @return JSON formatted string
     *
     * Usage scenario: Convert business parameter objects to JSON strings,
     *                 preparing for subsequent encryption operations.
     *
     * Example:
     * Map<String, Object> params = new HashMap<>();
     * params.put("key", "value");
     * String json = JsonUtils.toJson(params);
     */
    public static String toJson(Object object) throws Exception {
        return mapper.writeValueAsString(object);
    }

    /**
     * Deserialize JSON string to object
     *
     * @param json JSON formatted string
     * @param clazz Target object class
     * @return Deserialized Java object
     *
     * Usage scenario: Convert decrypted JSON data to business objects,
     *                 extracting data content returned from the server.
     *
     * Example:
     * AddressVO address = JsonUtils.fromJson(
     *     jsonData,
     *     AddressVO.class
     * );
     */
    public static <T> T fromJson(String json, Class<T> clazz) throws Exception {
        return mapper.readValue(
            json.getBytes(StandardCharsets.UTF_8),
            clazz
        );
    }
}