NipGeihou's blog NipGeihou's blog
  • Java

    • 开发规范
    • 进阶笔记
    • 微服务
    • 快速开始
    • 设计模式
  • 其他

    • Golang
    • Python
    • Drat
  • Redis
  • MongoDB
  • 数据结构与算法
  • 计算机网络
  • 应用

    • Grafana
    • Prometheus
  • 容器与编排

    • KubeSphere
    • Kubernetes
    • Docker Compose
    • Docker
  • 组网

    • TailScale
    • WireGuard
  • 密码生成器
  • 英文单词生成器
🍳烹饪
🧑‍💻关于
  • 分类
  • 标签
  • 归档

NipGeihou

我见青山多妩媚,料青山见我应如是
  • Java

    • 开发规范
    • 进阶笔记
    • 微服务
    • 快速开始
    • 设计模式
  • 其他

    • Golang
    • Python
    • Drat
  • Redis
  • MongoDB
  • 数据结构与算法
  • 计算机网络
  • 应用

    • Grafana
    • Prometheus
  • 容器与编排

    • KubeSphere
    • Kubernetes
    • Docker Compose
    • Docker
  • 组网

    • TailScale
    • WireGuard
  • 密码生成器
  • 英文单词生成器
🍳烹饪
🧑‍💻关于
  • 分类
  • 标签
  • 归档
  • 设计模式

  • 开发规范

  • 经验分享

  • 记录

  • 快速开始

  • 笔记

    • 多线程与并发

    • JDK

    • Java集合

    • Spring

    • JVM

    • Other

      • jackson
        • 初始化
        • 使用
          • 含泛型的反序列化
          • 下换线转小驼峰
          • 反序列化
        • 工具类
      • Maven
  • 面试题

  • 微服务

  • 踩过的坑

  • Java
  • 笔记
  • Other
NipGeihou
2023-11-14
目录

jackson

# 初始化

# 使用

# 含泛型的反序列化

JSON 反序列化,即 JSON 字符串转 Java 对象

// Resp对象属性存在泛型时,使用TypeReference
objectMapper.readValue(jsonStr,new TypeReference<HaodankuResp<List<GoodsItem>>>(){})
    
// 不存在泛型时,可使用Class对象
objectMapper.readValue(jsonStr,GoodsItem.class)

# 下换线转小驼峰

// 方式1
@Bean
public Jackson2ObjectMapperBuilderCustomizer customizer() {
    return builder -> {
        ...

        // json下划线转小驼峰
        builder.propertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
        log.info("初始化 jackson 配置");
    };
}

// 方式2
objectMapper = new ObjectMapper();
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);

// 方式3
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public static class Request {

    String businessName;
    String businessLegalName;

}

笔记

如果仅仅是因为某些 API 接口的返回是下划线命名,建议使用 方式3 单独在对应的 DTO 类上添加 @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class) ,而不是使用 方式1、2 的全局处理,这会导致控制器接收 json 入参时也需要使用下划线命名,否则映射不到。

# 反序列化

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValueAsString(user);

# 工具类

点击查看
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.core.utils.StringUtils;

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

/**
 * JSON 工具类
 *
 * @author 芋道源码
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class JsonUtils {

    private static final ObjectMapper OBJECT_MAPPER;

    static {
        ObjectMapper objectMapper;
        try {
            objectMapper = SpringUtils.getBean(ObjectMapper.class);
        } catch (Exception e) {
            // 非Spring环境使用
            objectMapper = new ObjectMapper();
        }
        OBJECT_MAPPER = objectMapper;
    }

    public static ObjectMapper getObjectMapper() {
        return OBJECT_MAPPER;
    }

    public static String toJsonString(Object object) {
        if (ObjectUtil.isNull(object)) {
            return null;
        }
        try {
            return OBJECT_MAPPER.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T parseObject(String text, Class<T> clazz) {
        if (StringUtils.isEmpty(text)) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(text, clazz);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T parseObject(byte[] bytes, Class<T> clazz) {
        if (ArrayUtil.isEmpty(bytes)) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(bytes, clazz);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T parseObject(String text, TypeReference<T> typeReference) {
        if (StringUtils.isBlank(text)) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(text, typeReference);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static Dict parseMap(String text) {
        if (StringUtils.isBlank(text)) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(text, OBJECT_MAPPER.getTypeFactory().constructType(Dict.class));
        } catch (MismatchedInputException e) {
            // 类型不匹配说明不是json
            return null;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static List<Dict> parseArrayMap(String text) {
        if (StringUtils.isBlank(text)) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(text, OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, Dict.class));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> List<T> parseArray(String text, Class<T> clazz) {
        if (StringUtils.isEmpty(text)) {
            return new ArrayList<>();
        }
        try {
            return OBJECT_MAPPER.readValue(text, OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}

上次更新: 2023/12/05, 17:33:37
JVM 基础 - JVM内存结构(运行时数据区)
Maven

← JVM 基础 - JVM内存结构(运行时数据区) Maven→

最近更新
01
iSCSI服务搭建
05-10
02
磁盘管理与文件系统
05-02
03
网络测试 - iperf3
05-02
更多文章>
Theme by Vdoing | Copyright © 2018-2025 NipGeihou | 友情链接
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式