java对象和json对象互转

在网上找了一大堆 没找到合适的

java 复制代码
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

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

@Slf4j
public class JsonUtil {
    public static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        //反序列化时,忽略目标对象没有的属性
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    }

    public static String toJsonString(Object o) {
        try {
            return objectMapper.writeValueAsString(o);
        } catch (Exception e) {
            log.error("JsonProcessingException:", e);
        }
        return "";
    }

    public static <T> T toObject(String s, Class<T> var) {
        try {
            return objectMapper.readValue(s, var);
        } catch (IOException e) {
            log.error("IOException:", e);
        }
        return null;
    }


    public static <T> List<T> toList(String s, Class<T> var) {
        try {
            JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, var);
            return objectMapper.readValue(s, javaType);
        } catch (IOException e) {
            log.error("IOException:", e);
        }
        return null;
    }

}
相关推荐
一 乐几秒前
幼儿园管理|基于springboot + vue幼儿园管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端
JH灰色几秒前
【大模型】-LangChain多模态输入和自定义输出
java·前端·langchain
JIngJaneIL1 分钟前
基于Java + vue校园论坛系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
Mcband8 分钟前
forEach跳出循环
java
期待のcode10 分钟前
Springboot多数据源配置
java·数据库·spring boot·后端·mybatis
Knight_AL15 分钟前
深入解析 Spring 循环依赖:如何通过三级缓存解决 A ↔ B 的依赖问题
java·spring·缓存
零小陈上(shouhou6668889)20 分钟前
YOLOv8+PyQt5海洋船只检测(可以重新训练,yolov8模型,从图像、视频和摄像头三种路径识别检测)
开发语言·python·yolo
znhy_2323 分钟前
day36打卡
python