欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Json工具类

程序员文章站 2024-02-02 21:44:46
...

在工程中定义此类,方便以后进行json数据转换逻辑操作。

package com.example.demo.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class JsonUtil {
    private static ObjectMapper objectMapper = new ObjectMapper();

    private JsonUtil() {

    }

    public static ObjectNode createObject() { //大括号
        return objectMapper.createObjectNode();
    }

    public static ArrayNode createArray() { //中括号
        return objectMapper.createArrayNode();
    }

    public static JsonNodeFactory getFactory() {
        return objectMapper.getNodeFactory();
    }

    public static String toJson(Object obj) {
        String json = null;
        try {
            json = objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return json;
    }

    public static JsonNode fromJson(String json) {
        JsonNode jsonNode = null;
        try {
            jsonNode = objectMapper.readValue(json, JsonNode.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return jsonNode;
    }

    public static ObjectNode fromObject(String json) {
        return (ObjectNode) fromJson(json);
    }

    public static <T> T fromObject(String json, Class<T> tClass) {
        try {
            return objectMapper.readValue(json, tClass);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T fromObject(ObjectNode node, Class<T> tClass) {
        return fromObject(toJson(node), tClass);
    }

    public static ArrayNode fromArray(String json) {
        return (ArrayNode) fromJson(json);
    }

    public static <T> List<T> fromArray(String json, Class<T> tClass) {
        JavaType javaType = getCollectionType(ArrayList.class, tClass);
        List<T> list = null;
        try {
            list = objectMapper.readValue(json, javaType);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return list;
    }

    public static <T> List<T> fromArray(ArrayNode node, Class<T> tClass) {
        return fromArray(toJson(node), tClass);
    }

    private static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
        return objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }
}
相关标签: Json使用