【JSON篇】————Jackson使用/配置/工具类

Jackson——对象转json/对象转json

public class JackSon_Test_01 {
    @Data
    @ToString
    public static class Person {
        private int id;
        private String name;
        private String password;

        public Person() {
            super();
        }

        public Person(int id, String name, String password) {
            this.id = id;
            this.name = name;
            this.password = password;
        }
        /*省略get和set方法*/
    }
    public static void main(String[] args) throws Exception{
       /*
         对象转JSON
        */
        Person startObject = new Person(1, "tom", "123");
        ObjectMapper objectMapper=new ObjectMapper();
        String startObjectJson = objectMapper.writeValueAsString(startObject);

        System.out.println("startObjectJson: " + startObjectJson);
       /*
         JSON转对象
        */
        Person deSerializationObject = objectMapper.readValue(startObjectJson, Person.class);
        System.out.println(deSerializationObject.toString());
    }
}

Jackson——json转数组/数组转json

public static void main(String[] args) throws Exception{
        ObjectMapper objectMapper = new ObjectMapper();
        /**
         * Java数组转JSON
         */
        List<Person> personList = new ArrayList<>();
        personList.add(new Person(1, "tom", "123"));
        personList.add(new Person(2, "jack", "123445"));
        String jsonArrayString = objectMapper.writeValueAsString(personList);
        System.out.println("jsonArrayString: " + jsonArrayString);
        /*
         * JSON转JAVA数组
         * 需要用TypeFactory构造出JavaType传给Jackson让其能根据class类型构造出数组内的java对象
         */
        JavaType javaType = objectMapper
                .getTypeFactory()
                .constructParametricType(List.class, Person.class);
        List<Person> list = objectMapper.readValue(jsonArrayString,javaType);
        System.out.println(list.toString());
    }

Jackson——objectMapper基本配置

     ObjectMapper mapper=new ObjectMapper();
        /**
         * @配置序列化JsonIncluede注解
         */
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);//只序列化不是null的
        mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS); //序列化的时候序列对象的所有属性
        mapper.setSerializationInclusion(JsonInclude.Include.NON_ABSENT);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);//序列化时不包含无默认值的
        mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);//只序列化不是空的,数组空或者字符串空
        mapper.setSerializationInclusion(JsonInclude.Include.USE_DEFAULTS);//使用默认值
        /**
         * @配置一些开关
         * 规则————抛出异常
         * 方式————自动转化
         */
        mapper.configure(SerializationFeature.EAGER_SERIALIZER_FETCH,false);//SerializationFeature——————一些序列化规则的开关
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);//DeserializationFeature——————反序列化规则的开关
        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES,false);//JsonParser枚举——————一些解析规则的开关
        mapper.configure(MapperFeature.AUTO_DETECT_CREATORS,false);//MapperFeature枚举——————一些自动转化开关

Jackson——工具类


public class JackSonUtils {
      private static final ObjectMapper MAPPER = new ObjectMapper();
    static {
        MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);//序列化的时候序列对象,bean的属性设置
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);//反序列化的时候如果多了其它属性,不抛出异常
        MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);//如果是空对象的时候,不抛异常
        MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);//取消时间的转换格式,默认是时间戳,同时需设置时间格式
        MAPPER.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
    }
    public static String objectToJson(Object data) {
        try {
            String result = MAPPER.writeValueAsString(data);
            return result;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T jsonToBean(String jsonData, Class<T> beanType) {
        try {
            T result = MAPPER.readValue(jsonData, beanType);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) {
        JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
        try {
            List<T> resultList = MAPPER.readValue(jsonData, javaType);
            return resultList;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static <K, V> Map<K, V> jsonToMap(String jsonData, Class<K> keyType, Class<V> valueType) {
        JavaType javaType = MAPPER.getTypeFactory().constructMapType(Map.class, keyType, valueType);

        try {
            Map<K, V> resultMap = MAPPER.readValue(jsonData, javaType);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值