json转bean

该文章提供了一个名为JacksonUtil的Java类,该类利用Jackson库进行对象到JSON及JSON到对象的转换。类中包含多个静态方法,如beanToJson、jsonToBean,支持不同类型转换并处理异常情况。
摘要由CSDN通过智能技术生成

import java.io.IOException;
import java.io.StringWriter;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Jackson 对象与json互转工具类
 */
public class JacksonUtil {

    private static ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    public static final Logger LOGGER = LoggerFactory.getLogger(JacksonUtil.class);


    public static String beanToJson(Object obj) {
        StringWriter sw = new StringWriter();
        try{
            JsonGenerator gen = new JsonFactory().createGenerator(sw);
            mapper.writeValue(gen, obj);
            gen.close();
        } catch (IOException e) {
            LOGGER.error("bean = {} to json error = {} !", obj, e);
            e.printStackTrace();
        }
        return sw.toString();
    }


    public static <T> T jsonToBean(String jsonStr, Class<T> objClass) {
        try{
            return mapper.readValue(jsonStr, objClass);
        } catch (IOException e) {
            LOGGER.error("json = {} to objClass = {} error = {} !", jsonStr, objClass, e);
            e.printStackTrace();
        }
        return null;
    }


    public static <T> T jsonToBean(String jsonStr, JavaType javaType) {
        try{
            return (T) mapper.readValue(jsonStr, javaType);
        } catch (IOException e) {
            LOGGER.error("json = {} to javaType = {} error = {} !", jsonStr, javaType, e);
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T jsonToBean(String jsonStr, TypeReference valueTypeRef) {
        try {
            return mapper.readValue(jsonStr, valueTypeRef);
        } catch (IOException e) {
            LOGGER.error("json = {} to objClass = {} error = {} !", jsonStr, valueTypeRef.getClass(), e);
            e.printStackTrace();
        }
        return null;
    }

    public static String writeValueAsString(Object bean) {
        try {
            return mapper.writeValueAsString(bean);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值