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      泛型
     */
    public static <T> T parse(String jsonStr, Class<T> clazz) {
        return parse(jsonStr, clazz, null);
    }

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

    /**
     * json => 对象处理方法
     * 
* 参数clazz和type必须一个为null,另一个不为null *
* 此方法不对外暴露,访问权限为private * * @param jsonStr 源json串 * @param clazz 对象类 * @param type 对象类型 * @param 泛型 */
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}]
在这里插入图片描述

你可能感兴趣的:(项目管理,Java,java)