重新整理了新版JSON工具类和一些见解

封装好了,工具类,直接粘贴就好了:所需依赖 springboot,hutool

java 复制代码
package com.jmj.gulimall.product.utils;

import cn.hutool.core.bean.BeanUtil;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
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.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.util.StdDateFormat;
import com.jmj.gulimall.product.vo.spu.Attr;
import lombok.*;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class JsonUtils {

    private final static ObjectMapper objectMapper;

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @EqualsAndHashCode(callSuper = true)//不加这个情况下重写的Hashcode和Equals 不会比较父类属性值
    @ToString(callSuper = true)//包括父类
    @JsonIgnoreProperties({"attrValue","attrId","attrName"})//这个注解可以忽略父类属性,不需要spring环境
    public static class Energy extends Attr {
        @JsonIgnore//忽略本类字段
        private String name;
        private Date time;
    }

    public static ObjectMapper instance(DateFormat dateFormat){
        ObjectMapper objectMapper = new ObjectMapper();
        //{"name":"边杰","time":"2024-06-21T10:43:43.480+0000"}
        objectMapper.setDateFormat(dateFormat);//中间没有:号
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);//禁用转换时间戳
        // 序列化时忽略未知属性
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 禁用忽略大小写的特性
        objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, false);

        // 设置序列化时不包含空属性
        // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // 不包括null值
        objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS); // 全部
        return objectMapper;
    }
    public static ObjectMapper instance(){
        return instance(new StdDateFormat().withColonInTimeZone(false));
    }
    static {
       objectMapper = instance();
    }
    public static DateFormat format(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simpleDateFormat;
    }

    public static String getJson(Object obj, boolean exIsThrow) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            if (exIsThrow) {
                throw new RuntimeException("JSON解析异常 e=" + e.getMessage());
            } else {
                return null;
            }

        }
    }

    public static String getJson(Object obj) {
        return getJson(obj, false);
    }

    public static <R> R getObj(String json, Class<R> clazz, boolean exIsThrow) {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            if (exIsThrow) {
                throw new RuntimeException("JSON解析异常 e=" + e.getMessage());
            } else {
                return null;
            }
        }
    }
    public static <R> R getObj(String json, Class<R> clazz) {
        return getObj(json, clazz, false);
    }

    public static <T> T getObj(String json,TypeReference<T> type, boolean exIsThrow) {
        try {
            return objectMapper.readValue(json, type);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            if (exIsThrow) {
                throw new RuntimeException("JSON解析异常 e=" + e.getMessage());
            } else {
                return null;
            }
        }

    }

    public static <T> T getObj(String json,TypeReference<T> type) {
        return getObj(json, type,false);
    }


    public static void main(String[] args) throws JsonProcessingException {
//        List<Energy> list = Arrays.asList(new Energy("边界", new Date()), new Energy("边界", new Date()), new Energy("边界", new Date()));
//        String s = getJson(list);
//        System.out.println(s);
//        List<Energy> energy = getObj("[{\"attrId\":\"123\",\"attrName\":null,\"name\":\"边界\",\"time\":\"2024-06-21T11:59:00.118+0000\"},{\"attrId\":null,\"attrName\":null,\"name\":\"边界\",\"time\":\"2024-06-21T11:59:00.118+0000\"},{\"attrId\":null,\"attrName\":null,\"name\":\"边界\",\"time\":\"2024-06-21T11:59:00.118+0000\"}]",
//                new TypeReference<List<Energy>>() {},true);
//        System.out.println(energy);

//        System.out.println(instance(format()).writeValueAsString(list));


        Energy energy = new Energy("边界", new Date());
        energy.setAttrId(123L);
        energy.setAttrName("a");
        energy.setAttrValue("as");

        System.out.println(getJson(energy));
        
        
        Attr attr = new Attr();
        //父类属性也会Copy过来
        BeanUtil.copyProperties(energy,attr);
        System.out.println(attr);

    }


}
相关推荐
牢七几秒前
jfinal_cms-v5.1.0 白盒 nday
开发语言·python
ayt00711 分钟前
Netty 4.2核心类解析:SingleThreadIoEventLoop的设计哲学与实现
java·网络
无名-CODING13 分钟前
Java 爬虫进阶:动态网页、多线程与 WebMagic 框架实战
java·爬虫·okhttp
weixin_7042660515 分钟前
Spring 注解驱动开发与 Spring Boot 核心知识点梳理
java·spring boot·spring
开开心心就好16 分钟前
伪装文件历史记录!修改时间的黑科技软件
java·前端·科技·r语言·edge·pdf·语音识别
纤纡.17 分钟前
基于 PyTorch 手动实现 CBOW 词向量训练详解
人工智能·pytorch·python·深度学习
8Qi819 分钟前
Redis哨兵模式(Sentinel)深度解析
java·数据库·redis·分布式·缓存·sentinel
词元Max21 分钟前
2.5 Python 类型注解与运行时类型检查
开发语言·python
沪漂阿龙23 分钟前
深度解析Pandas数据组合:从concat到merge,打通你的数据处理任督二脉
python·数据分析·pandas
wangchunting26 分钟前
数据结构-树
java·数据结构