JsonUtil

<!-- ObjectMapper -->
    <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.18.1</version>
        </dependency>

fastJson


// 正确的传参方式如下

// arr.forEach((value, index) => {
//   fd.append(`address[${index}].name`, value.name)
//   fd.append(`address[${index}].age`, value.age)
// })
// 如果是字符串或者数字数组

// const arr = [1, 2, 3, 4, 5]

// arr.forEach((value, index) => {
//   fd.append(`address[${index}]`, value)
// })



package org.air.app.common.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.air.app.bsw.controller.AppBswController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * @author hanzq@aircas.ac.cn
 * @version 1.0
 * @description: TODO
 * @date 2024/11/7 17:30
 */
public class FastJsonUtil {

        private static final Logger log = LoggerFactory.getLogger(AppBswController.class);

        private static ObjectMapper objectMapper = new ObjectMapper();

        // 时间日期格式
        private static final String STANDARD_FORMAT = "yyyy-MM-dd HH:mm:ss";

        //以静态代码块初始化
        static {
            //对象的所有字段全部列入序列化
            objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
            //取消默认转换timestamps形式
            objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
            //忽略空Bean转json的错误
            objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
            //所有的日期格式都统一为以下的格式,即yyyy-MM-dd HH:mm:ss
            objectMapper.setDateFormat(new SimpleDateFormat(STANDARD_FORMAT));
            //忽略 在json字符串中存在,但在java对象中不存在对应属性的情况。防止错误
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        }


        /**===========================以下是从JSON中获取对象====================================*/
        public static <T> T parseObject(String jsonString, Class<T> object) {
            T t = null;
            try {
                t = objectMapper.readValue(jsonString, object);
            } catch (JsonProcessingException e) {
                log.error("JsonString转为自定义对象失败:{}", e.getMessage());
            }
            return t;
        }

        public static <T> T parseObject(File file, Class<T> object) {
            T t = null;
            try {
                t = objectMapper.readValue(file, object);
            } catch (IOException e) {
                log.error("从文件中读取json字符串转为自定义对象失败:{}", e.getMessage());
            }
            return t;
        }

        //将json数组字符串转为指定对象List列表或者Map集合
        public static <T> T parseJSONArray(String jsonArray, TypeReference<T> reference) {
            T t = null;
            try {
                t = objectMapper.readValue(jsonArray, reference);
            } catch (JsonProcessingException e) {
                log.error("JSONArray转为List列表或者Map集合失败:{}", e.getMessage());
            }
            return t;
        }


        /**=================================以下是将对象转为JSON=====================================*/
        public static String toJSONString(Object object) {
            String jsonString = null;
            try {
                jsonString = objectMapper.writeValueAsString(object);
            } catch (JsonProcessingException e) {
                log.error("Object转JSONString失败:{}", e.getMessage());
            }
            return jsonString;
        }

        public static byte[] toByteArray(Object object) {
            byte[] bytes = null;
            try {
                bytes = objectMapper.writeValueAsBytes(object);
            } catch (JsonProcessingException e) {
                log.error("Object转ByteArray失败:{}", e.getMessage());
            }
            return bytes;
        }

        public static void objectToFile(File file, Object object) {
            try {
                objectMapper.writeValue(file, object);
            } catch (JsonProcessingException e) {
                log.error("Object写入文件失败:{}", e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        /**=============================以下是与JsonNode相关的=======================================*/
        //JsonNode和JSONObject一样,都是JSON树形模型,只不过在jackson中,存在的是JsonNode
        public static JsonNode parseJSONObject(String jsonString) {
            JsonNode jsonNode = null;
            try {
                jsonNode = objectMapper.readTree(jsonString);
            } catch (JsonProcessingException e) {
                log.error("JSONString转为JsonNode失败:{}", e.getMessage());
            }
            return jsonNode;
        }

        public static JsonNode parseJSONObject(Object object) {
            JsonNode jsonNode = objectMapper.valueToTree(object);
            return jsonNode;
        }

        public static String toJSONString(JsonNode jsonNode) {
            String jsonString = null;
            try {
                jsonString = objectMapper.writeValueAsString(jsonNode);
            } catch (JsonProcessingException e) {
                log.error("JsonNode转JSONString失败:{}", e.getMessage());
            }
            return jsonString;
        }

        //JsonNode是一个抽象类,不能实例化,创建JSON树形模型,得用JsonNode的子类ObjectNode,用法和JSONObject大同小异
        public static ObjectNode newJSONObject() {
            return objectMapper.createObjectNode();
        }

        //创建JSON数组对象,就像JSONArray一样用
        public static ArrayNode newJSONArray() {
            return objectMapper.createArrayNode();
        }


        /**===========以下是从JsonNode对象中获取key值的方法,个人觉得有点多余,直接用JsonNode自带的取值方法会好点,出于纠结症,还是补充进来了*/
        public static String getString(JsonNode jsonObject, String key) {
            String s = jsonObject.get(key).asText();
            return s;
        }

        public static Integer getInteger(JsonNode jsonObject, String key) {
            Integer i = jsonObject.get(key).asInt();
            return i;
        }

        public static Boolean getBoolean(JsonNode jsonObject, String key) {
            Boolean bool = jsonObject.get(key).asBoolean();
            return bool;
        }

        public static JsonNode getJSONObject(JsonNode jsonObject, String key) {
            JsonNode json = jsonObject.get(key);
            return json;
        }
 




}

  • 其他
 
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;

/**
 * <p>
 * JSON与对象互转帮助类
 * </p>
 
 */
@Slf4j
public class JsonUtils {

    private JsonUtils() {
        // 禁止实例化工具类
        throw new UnsupportedOperationException("Utility classes cannot be instantiated.");
    }

    /**
     * 设置为public是为了提供给redis的序列化器
     */
    private final static ObjectMapper MAPPER = new ObjectMapper();

    static {
        // 对象的所有字段全部列入,还是其他的选项,可以忽略null等
        MAPPER.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        // 取消默认的时间转换为timeStamp格式
        MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        // 设置Date类型的序列化及反序列化格式
        MAPPER.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        // 忽略空Bean转json的错误
        MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        // 忽略未知属性,防止json字符串中存在,java对象中不存在对应属性的情况出现错误
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 添加java8序列化支持和新版时间对象序列化支持
        MAPPER.registerModule(new Jdk8Module());
        MAPPER.registerModule(new JavaTimeModule());
    }

    /**
     * json字符串转为对象
     *
     * @param json  json
     * @param clazz T类的class文件
     * @param <T>   泛型, 代表返回参数的类型
     * @return 返回T的实例
     */
    public static <T> T jsonCovertToObject(String json, Class<T> clazz) {
        if (json == null || clazz == null) {
            return null;
        }
        try {
            return MAPPER.readValue(json, clazz);
        } catch (IOException e) {
            log.error("json转换失败,原因:", e);
        }
        return null;
    }

    /**
     * json字符串转为对象
     *
     * @param json json
     * @param type 对象在Jackson中的类型
     * @param <T>  泛型, 代表返回参数的类型
     * @return 返回T的实例
     */
    public static <T> T jsonCovertToObject(String json, TypeReference<T> type) {
        if (json == null || type == null) {
            return null;
        }
        try {
            return MAPPER.readValue(json, type);
        } catch (IOException e) {
            log.error("json转换失败,原因:", e);
        }
        return null;
    }

    /**
     * 将流中的数据转为java对象
     *
     * @param inputStream 输入流
     * @param clazz       类的class
     * @param <T>         泛型, 代表返回参数的类型
     * @return 返回对象 如果参数任意一个为 null则返回null
     */
    public static <T> T covertStreamToObject(InputStream inputStream, Class<T> clazz) {
        if (inputStream == null || clazz == null) {
            return null;
        }
        try {
            return MAPPER.readValue(inputStream, clazz);
        } catch (IOException e) {
            log.error("json转换失败,原因:", e);
        }
        return null;
    }

    /**
     * json字符串转为复杂类型List
     *
     * @param json            json
     * @param collectionClazz 集合的class
     * @param elementsClazz   集合中泛型的class
     * @param <T>             泛型, 代表返回参数的类型
     * @return 返回T的实例
     */
    public static <T> T jsonCovertToObject(String json, Class<?> collectionClazz, Class<?>... elementsClazz) {
        if (json == null || collectionClazz == null || elementsClazz == null || elementsClazz.length == 0) {
            return null;
        }
        try {
            JavaType javaType = MAPPER.getTypeFactory().constructParametricType(collectionClazz, elementsClazz);
            return MAPPER.readValue(json, javaType);
        } catch (IOException e) {
            log.error("json转换失败,原因:", e);
        }
        return null;
    }

    /**
     * 对象转为json字符串
     *
     * @param o 将要转化的对象
     * @return 返回json字符串
     */
    public static String objectCovertToJson(Object o) {
        if (o == null) {
            return null;
        }
        try {
            return o instanceof String ? (String) o : MAPPER.writeValueAsString(o);
        } catch (IOException e) {
            log.error("json转换失败,原因:", e);
        }
        return null;
    }

    /**
     * 将对象转为另一个对象
     * 切记,两个对象结构要一致
     * 多用于Object转为具体的对象
     *
     * @param o               将要转化的对象
     * @param collectionClazz 集合的class
     * @param elementsClazz   集合中泛型的class
     * @param <T>             泛型, 代表返回参数的类型
     * @return 返回T的实例
     */
    public static <T> T objectCovertToObject(Object o, Class<?> collectionClazz, Class<?>... elementsClazz) {
        String json = objectCovertToJson(o);
        return jsonCovertToObject(json, collectionClazz, elementsClazz);
    }

}





import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * JSON 工具类
 *
 * @author 芋道源码
 */
@Slf4j
public class JsonUtils {

    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // 忽略 null 值
        objectMapper.registerModules(new JavaTimeModule()); // 解决 LocalDateTime 的序列化
    }

    /**
     * 初始化 objectMapper 属性
     * <p>
     * 通过这样的方式,使用 Spring 创建的 ObjectMapper Bean
     *
     * @param objectMapper ObjectMapper 对象
     */
    public static void init(ObjectMapper objectMapper) {
        JsonUtils.objectMapper = objectMapper;
    }

    @SneakyThrows
    public static String toJsonString(Object object) {
        return objectMapper.writeValueAsString(object);
    }

    @SneakyThrows
    public static byte[] toJsonByte(Object object) {
        return objectMapper.writeValueAsBytes(object);
    }

    @SneakyThrows
    public static String toJsonPrettyString(Object object) {
        return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
    }

    public static <T> T parseObject(String text, Class<T> clazz) {
        if (StrUtil.isEmpty(text)) {
            return null;
        }
        try {
            return objectMapper.readValue(text, clazz);
        } catch (IOException e) {
            log.error("json parse err,json:{}", text, e);
            throw new RuntimeException(e);
        }
    }

    public static <T> T parseObject(String text, String path, Class<T> clazz) {
        if (StrUtil.isEmpty(text)) {
            return null;
        }
        try {
            JsonNode treeNode = objectMapper.readTree(text);
            JsonNode pathNode = treeNode.path(path);
            return objectMapper.readValue(pathNode.toString(), clazz);
        } catch (IOException e) {
            log.error("json parse err,json:{}", text, e);
            throw new RuntimeException(e);
        }
    }

    public static <T> T parseObject(String text, Type type) {
        if (StrUtil.isEmpty(text)) {
            return null;
        }
        try {
            return objectMapper.readValue(text, objectMapper.getTypeFactory().constructType(type));
        } catch (IOException e) {
            log.error("json parse err,json:{}", text, e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 将字符串解析成指定类型的对象
     * 使用 {@link #parseObject(String, Class)} 时,在@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) 的场景下,
     * 如果 text 没有 class 属性,则会报错。此时,使用这个方法,可以解决。
     *
     * @param text 字符串
     * @param clazz 类型
     * @return 对象
     */
    public static <T> T parseObject2(String text, Class<T> clazz) {
        if (StrUtil.isEmpty(text)) {
            return null;
        }
        return JSONUtil.toBean(text, clazz);
    }

    public static <T> T parseObject(byte[] bytes, Class<T> clazz) {
        if (ArrayUtil.isEmpty(bytes)) {
            return null;
        }
        try {
            return objectMapper.readValue(bytes, clazz);
        } catch (IOException e) {
            log.error("json parse err,json:{}", bytes, e);
            throw new RuntimeException(e);
        }
    }

    public static <T> T parseObject(String text, TypeReference<T> typeReference) {
        try {
            return objectMapper.readValue(text, typeReference);
        } catch (IOException e) {
            log.error("json parse err,json:{}", text, e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 解析 JSON 字符串成指定类型的对象,如果解析失败,则返回 null
     *
     * @param text 字符串
     * @param typeReference 类型引用
     * @return 指定类型的对象
     */
    public static <T> T parseObjectQuietly(String text, TypeReference<T> typeReference) {
        try {
            return objectMapper.readValue(text, typeReference);
        } catch (IOException e) {
            return null;
        }
    }

    public static <T> List<T> parseArray(String text, Class<T> clazz) {
        if (StrUtil.isEmpty(text)) {
            return new ArrayList<>();
        }
        try {
            return objectMapper.readValue(text, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
        } catch (IOException e) {
            log.error("json parse err,json:{}", text, e);
            throw new RuntimeException(e);
        }
    }

    public static <T> List<T> parseArray(String text, String path, Class<T> clazz) {
        if (StrUtil.isEmpty(text)) {
            return null;
        }
        try {
            JsonNode treeNode = objectMapper.readTree(text);
            JsonNode pathNode = treeNode.path(path);
            return objectMapper.readValue(pathNode.toString(), objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
        } catch (IOException e) {
            log.error("json parse err,json:{}", text, e);
            throw new RuntimeException(e);
        }
    }

    public static JsonNode parseTree(String text) {
        try {
            return objectMapper.readTree(text);
        } catch (IOException e) {
            log.error("json parse err,json:{}", text, e);
            throw new RuntimeException(e);
        }
    }

    public static JsonNode parseTree(byte[] text) {
        try {
            return objectMapper.readTree(text);
        } catch (IOException e) {
            log.error("json parse err,json:{}", text, e);
            throw new RuntimeException(e);
        }
    }

    public static boolean isJson(String text) {
        return JSONUtil.isTypeJSON(text);
    }

}