【fasterxml】json 工具类

本文介绍了一个用于处理JSON数据的工具类,包括将JSON字符串转换为Java对象、转换为对象列表及将Java对象转换为JSON字符串的功能。该工具类通过自定义配置增强了序列化和反序列化的灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

直接贴代码,方便下次使用。

/**
 * json 工具类
 * <p>
 * Created by xlch at 2018/6/26
 */
public class JsonUtil {


    private JsonUtil() {

    }

    private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtil.class);

    private static final ObjectMapper mapper = new ObjectMapper();


    static {
        // 序列化时 是否包含 null 字段:不包含
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //反序列化时是否忽略 不存在的属性值:忽略
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 下划线转为驼峰
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE);

    }


    public  static <T> T json2Object(String source, Class<T> classType) {
        try {
            return mapper.readValue(source, classType);
        } catch (IOException e) {
            LOGGER.debug("exception is ", e);
            throw new VastioException("json 读取出错");
        }
    }

    public static <T> List<T> json2ObjectList(String source, Class<T> classType) {
        JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, classType);
        try {
            return mapper.readValue(source, javaType);
        } catch (IOException e) {
            LOGGER.debug("exception is ", e);
            throw new VastioException("json list 读取出错");
        }
    }

    public static <T> String objects2Json(T source) {
        try {
            return mapper.writeValueAsString(source);
        } catch (JsonProcessingException e) {
            LOGGER.debug("exception is {}", e);
            throw new VastioException("json 写入出错");
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值