JsonUtils

1、工具类

package com.atguigu.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.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * 基于Jackson的JSON转换工具类
 *
 * @author: XuXin
 * @date: 2023/9/18
 */
@Slf4j
public class JsonUtils {
    // 定义jackson对象
    private static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        // 对象的所有字段全部列入,还是其他的选项,可以忽略null等
        objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        // 设置Date类型的序列化及反序列化格式
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        // 忽略空Bean转json的错误
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        // 忽略未知属性,防止json字符串中存在,java对象中不存在对应属性的情况出现错误
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 注册一个时间序列化及反序列化的处理模块,用于解决jdk8中localDateTime等的序列化问题
        objectMapper.registerModule(new JavaTimeModule()
                .addSerializer(LocalDateTime.class,
                        new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                .addDeserializer(LocalDateTime.class,
                        new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
        );
    }

    /**
     * 对象 => json字符串
     *
     * @param obj 源对象
     */
    public static String format(Object obj) {
        String json = null;
        if (obj != null) {
            try {
                json = objectMapper.writeValueAsString(obj);
            } catch (JsonProcessingException e) {
                log.warn(e.getMessage(), e);
                throw new IllegalArgumentException(e.getMessage());
            }
        }
        return json;
    }

    /**
     * json字符串 => 对象
     *
     * @param jsonStr 源json串
     * @param clazz   对象类
     * @param <T>     泛型
     */
    public static <T> T parse(String jsonStr, Class<T> clazz) {
        return parse(jsonStr, clazz, null);
    }

    /**
     * json字符串 => 对象
     *
     * @param jsonStr 源json串
     * @param type    对象类型
     * @param <T>     泛型
     */
    public static <T> T parse(String jsonStr, TypeReference<T> type) {
        return parse(jsonStr, null, type);
    }

    /**
     * json => 对象处理方法
     * <br>
     * 参数clazz和type必须一个为null,另一个不为null
     * <br>
     * 此方法不对外暴露,访问权限为private
     *
     * @param jsonStr 源json串
     * @param clazz   对象类
     * @param type    对象类型
     * @param <T>     泛型
     */
    private static <T> T parse(String jsonStr, Class<T> clazz, TypeReference<T> type) {
        T obj = null;
        if (!StringUtils.isEmpty(jsonStr)) {
            try {
                if (clazz != null) {
                    obj = objectMapper.readValue(jsonStr, clazz);
                } else {
                    obj = objectMapper.readValue(jsonStr, type);
                }
            } catch (IOException e) {
                log.warn(e.getMessage(), e);
                throw new IllegalArgumentException(e.getMessage());
            }
        }
        return obj;
    }

    public static <T> List<T> json2List(String jsonStr, Class<T> beanType) {
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, beanType);
        try {
            List<T> list = objectMapper.readValue(jsonStr, javaType);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

2、使用

@SpringBootTest
class MybatisplusApplicationTests {
    @Test
    void contextLoads() throws IOException {
        User user = new User();
        user.setName("pp");
        user.setAge(17);
        String s = JsonUtils3.format(user);
        User user1 = JsonUtils3.parse(s, User.class);
        User user2 = JsonUtils3.parse(s, new TypeReference<User>() {});
        Map<String, String> map = JsonUtils3.parse(s, new TypeReference<Map<String, String>>() {});
        String s2 = "[\n" +
                "{\"id\": 1, \"name\": \"John\"},\n" +
                "{\"id\": 2, \"name\": \"Jane\"},\n" +
                "{\"id\": 3, \"name\": \"Bob\"}\n" +
                "]";
        String s3 = "[{\"id\":null,\"name\":\"pp\",\"age\":17,\"email\":null,\"persion\":null}]";
        List<User> users1 = JsonUtils3.json2List(s2, User.class);
        List<User> users2 = JsonUtils3.json2List(s3, User.class);
    }
}

s:
{“id”:null,“name”:“pp”,“age”:17,“email”:null,“persion”:null}
s2:
[
{“id”: 1, “name”: “John”},
{“id”: 2, “name”: “Jane”},
{“id”: 3, “name”: “Bob”}
]
s3:
[{“id”:null,“name”:“pp”,“age”:17,“email”:null,“persion”:null}]
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值