基于Jackson的JSON工具类封装 JsonUtils

版权声明:原创欢迎转载,转载请注明出处 https://blog.csdn.net/ye17186/article/details/88692184

直接上代码,都有注释,一看就懂,完全满足日常开发需求

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.io.IOException;
import java.text.SimpleDateFormat;
import lombok.extern.slf4j.Slf4j;

/**
 * 基于Jackson的JSON转换工具类
 *
 * @author ye17186
 * @version 2018/6/29 12:06
 */
@Slf4j
public class JsonUtils {

    private static ObjectMapper om = new ObjectMapper();

    static {

        // 对象的所有字段全部列入,还是其他的选项,可以忽略null等
        om.setSerializationInclusion(Include.ALWAYS);
        // 设置Date类型的序列化及反序列化格式
        om.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

        // 忽略空Bean转json的错误
        om.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        // 忽略未知属性,防止json字符串中存在,java对象中不存在对应属性的情况出现错误
        om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        // 注册一个时间序列化及反序列化的处理模块,用于解决jdk8中localDateTime等的序列化问题
        om.registerModule(new JavaTimeModule());
    }

    /**
     * 对象 => json字符串
     *
     * @param obj 源对象
     */
    public static <T> String toJson(T obj) {

        String json = null;
        if (obj != null) {
            try {
                json = om.writeValueAsString(obj);
            } catch (JsonProcessingException e) {
                log.warn(e.getMessage(), e);
                throw new IllegalArgumentException(e.getMessage());
            }
        }
        return json;
    }

    /**
     * json字符串 => 对象
     *
     * @param json 源json串
     * @param clazz 对象类
     * @param <T> 泛型
     */
    public static <T> T parse(String json, Class<T> clazz) {

        return parse(json, clazz, null);
    }

    /**
     * json字符串 => 对象
     *
     * @param json 源json串
     * @param type 对象类型
     * @param <T> 泛型
     */
    public static <T> T parse(String json, TypeReference type) {

        return parse(json, null, type);
    }


    /**
     * json => 对象处理方法
     * <br>
     * 参数clazz和type必须一个为null,另一个不为null
     * <br>
     * 此方法不对外暴露,访问权限为private
     *
     * @param json 源json串
     * @param clazz 对象类
     * @param type 对象类型
     * @param <T> 泛型
     */
    private static <T> T parse(String json, Class<T> clazz, TypeReference type) {

        T obj = null;
        if (!StringUtils.isEmpty(json)) {
            try {
                if (clazz != null) {
                    obj = om.readValue(json, clazz);
                } else {
                    obj = om.readValue(json, type);
                }
            } catch (IOException e) {
                log.warn(e.getMessage(), e);
                throw new IllegalArgumentException(e.getMessage());
            }
        }
        return obj;
    }
}

如何使用就更简单了

public static void main(String[] args) {
    TestModel model1 = new TestModel();
    model1.setId("A");
    model1.setDate1(new Date());
    model1.setDate2(LocalDate.now());
    model1.setDate3(LocalDateTime.now());
    model1.setTime(LocalTime.now());

    TestModel2<TestModel> model2 = new TestModel2<>();
    model2.setId("PA");
    model2.setSub(model1);

    String json1 = JsonUtils.toJson(model1);
    String json2 = JsonUtils.toJson(model2);

    System.out.println(json1);
    System.out.println(json2);

    // 简单对象可以用这个
    TestModel obj1 = JsonUtils.parse(json1, TestModel.class);
    TestModel2<TestModel> obj2 = JsonUtils.parse(json2, TestModel2.class);
    // 需要准确泛型的复杂对象可以用这个,这种方式与上面有细微差别,读者可以自行debug研究
    TestModel2<TestModel> obj3 = JsonUtils
        .parse(json2, new TypeReference<TestModel2<TestModel>>() {
        });

    System.out.println(obj1);
    System.out.println(obj2);
    System.out.println(obj3);
}

程序输出:

GitHub地址:https://github.com/ye17186/spring-boot-learn

猜你喜欢

转载自blog.csdn.net/ye17186/article/details/88692184
今日推荐