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;
    }

}
相关推荐
Superstarimage1 小时前
使用conda创建python虚拟环境,并自定义路径
windows·python·conda
菜鸡码农,喵。1 小时前
已经装了pygame但pycharm显示没有该模块/软件包无法加载出来下载pygame
python·pycharm·pygame
Hello World......1 小时前
互联网大厂Java面试:从Spring到微服务的全面探讨
java·spring boot·spring cloud·微服务·面试·技术栈·互联网大厂
小羊Linux客栈1 小时前
自动化:批量文件重命名
运维·人工智能·python·自动化·游戏程序
拾贰_C2 小时前
【SpringBoot】MyBatisPlus(MP | 分页查询操作
java·spring boot·后端·spring·maven·apache·intellij-idea
猛踹瘸子那条好腿の2 小时前
Spring-boot初次使用
java·springboot
shykevin4 小时前
python开发Streamable HTTP MCP应用
开发语言·网络·python·网络协议·http
我不是程序猿儿4 小时前
【C#】 lock 关键字
java·开发语言·c#
漫路在线4 小时前
JS逆向-某易云音乐下载器
开发语言·javascript·爬虫·python
tmacfrank5 小时前
网络编程中的直接内存与零拷贝
java·linux·网络