基于Jackson封装的常用JSON操作API,特别适合于用习惯了Fastjson的开发者

由于Fastjson近来频繁出现各种漏洞,好多公司逐渐开始减少或禁止Fastjson的使用。除了Fastjson,市面上比较优秀的JSON类库还有很多,比较有名的比如Jackson、Gson等。

但是Jackson原生的API和Fastjson对比,使用起来稍微有些麻烦,因此本人参考Fastjson的基本使用API,封装了Jackson操作JSON的常用方法。

废话不多说,直接上代码。

1.maven依赖,引入jackson系列的所有依赖和Guava 工具类库

  <!--Jackson -->
  <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.11.3</version>
  </dependency>
  <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.11.3</version>
  </dependency>
  <dependency>
      <groupId>com.fasterxml.jackson.datatype</groupId>
      <artifactId>jackson-datatype-jdk8</artifactId>
      <version>2.11.3</version>
  </dependency>
  <dependency>
      <groupId>com.fasterxml.jackson.datatype</groupId>
      <artifactId>jackson-datatype-jsr310</artifactId>
      <version>2.11.3</version>
  </dependency>
  <dependency>
      <groupId>com.fasterxml.jackson.module</groupId>
      <artifactId>jackson-module-parameter-names</artifactId>
      <version>2.11.3</version>
  </dependency>
  <!--Guava 工具类库 -->
  <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>30.0-jre</version>
  </dependency>

2.Jackson工具类

package com.counter.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.databind.type.MapType;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * Jackson JSON工具类
 *
 * @author 2020/10/29
 */
public class JacksonUtil {
    private static ObjectMapper objectMapper = new ObjectMapper();

    private final static String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    private final static String DATE_FORMAT = "yyyy-MM-dd";
    private final static String TIME_FORMAT = "HH:mm:ss";
    /**
     * 默认日期格式化对象
     */
    private static ThreadLocal<SimpleDateFormat> formatLocal = ThreadLocal.withInitial(() -> new SimpleDateFormat(DATE_TIME_FORMAT));

    static {
        //在反序列化时忽略在 json 中存在但 Java 对象不存在的属性
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //在序列化时日期格式默认为 yyyy-MM-dd'T'HH:mm:ss.SSS
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        //在序列化时自定义默认时间日期格式(如果pojo使用了@JsonFormat注解指定日期格式,则会覆盖默认设置)
        objectMapper.setDateFormat(new SimpleDateFormat(DATE_TIME_FORMAT));
        //在序列化时忽略值为 null 的属性
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //POJO无public的属性或方法时,不报错
        objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        
        //设置按照字段名进行序列化
        objectMapper.setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE);
        objectMapper.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE);
        objectMapper.setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE);
        objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

        //针对于JDK新时间类。序列化时带有T的问题,自定义格式化字符串
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)));
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DATE_FORMAT)));
        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern((TIME_FORMAT))));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)));
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DATE_FORMAT)));
        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(TIME_FORMAT)));
        objectMapper.registerModule(javaTimeModule);
    }

    /**
     * 获取objectMapper对象
     *
     * @return ObjectMapper
     */
    public static ObjectMapper getObjectMapper() {
        return objectMapper;
    }

    //============================================== 序列化/反序列化 方法封装 =============================================================

    /**
     * 普通JSON序列化
     *
     * @param obj 目标对象
     * @return String
     */
    public static String toJSONString(Object obj) {
        if (obj == null) {
            return null;
        }
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException(e);
        }
    }

    /**
     * 格式化/美化/优雅 JSON序列化
     *
     * @param obj 目标对象
     * @return String
     */
    public static String toPrettyJSONString(Object obj) {
        if (obj == null) {
            return null;
        }
        try {
            return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException(e);
        }
    }

    /**
     * JSON字符串反序列化为Java对象
     *
     * @param jsonString JSON字符串
     * @param classType  对象类型
     * @return T
     */
    public static <T> T toJavaObject(String jsonString, Class<T> classType) {
        if (isEmpty(jsonString)) {
            return null;
        }
        try {
            return objectMapper.readValue(jsonString, classType);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException(e);
        }
    }

    /**
     * Object类型的对象转为指定的Java对象
     *
     * @param object    当前对象
     * @param classType 目标对象类型
     * @return T
     */
    public static <T> T toJavaObject(Object object, Class<T> classType) {
        if (object == null || isEmpty(object.toString())) {
            return null;
        }
        if (classType == null) {
            throw new IllegalArgumentException("classType is null!");
        }
        try {
            if (object instanceof String) {
                return objectMapper.readValue((String) object, classType);
            }
            return objectMapper.readValue(toJSONString(object), classType);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException(e);
        }
    }

    /**
     * JSON字符串反序列化为Map集合
     *
     * @param jsonString JSON字符串
     * @param keyType    key的泛型类型
     * @param valueType  value的泛型类型
     * @return Map<K, V>
     */
    public static <K, V> Map<K, V> toMap(String jsonString, Class<K> keyType, Class<V> valueType) {
        if (isEmpty(jsonString)) {
            return null;
        }
        if (keyType == null || valueType == null) {
            throw new IllegalArgumentException("keyType or valueType is null!");
        }
        try {
            //第二参数是 map 的 key 的类型,第三参数是 map 的 value 的类型
            MapType javaType = objectMapper.getTypeFactory().constructMapType(Map.class, keyType, valueType);
            return objectMapper.readValue(jsonString, javaType);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException(e);
        }
    }

    /**
     * JSON字符串反序列化为Map集合
     *
     * @param jsonString JSON字符串
     * @return Map<String, Object>
     */
    public static Map<String, Object> toMap(String jsonString) {
        return toMap(jsonString, String.class, Object.class);
    }

    /**
     * Object类型的对象转为Map集合
     *
     * @param object    当前对象
     * @param keyType   map的Key类型
     * @param valueType map的Value类型
     * @return Map<K, V>
     */
    public static <K, V> Map<K, V> toMap(Object object, Class<K> keyType, Class<V> valueType) {
        if (object == null || isEmpty(object.toString())) {
            return null;
        }
        if (keyType == null || valueType == null) {
            throw new IllegalArgumentException("keyType or valueType is null!");
        }
        try {
            //第二参数是 map 的 key 的类型,第三参数是 map 的 value 的类型
            MapType javaType = objectMapper.getTypeFactory().constructMapType(Map.class, keyType, valueType);
            if (object instanceof String) {
                return objectMapper.readValue((String) object, javaType);
            }
            return objectMapper.readValue(toJSONString(object), javaType);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException(e);
        }
    }

    public static Map<String, Object> toMap(Object object) {
        return toMap(object, String.class, Object.class);
    }

    /**
     * JSON字符串反序列化为List集合
     *
     * @param jsonString JSON字符串
     * @param classType  List的泛型
     * @return List<T>
     */
    public static <T> List<T> toList(String jsonString, Class<T> classType) {
        if (isEmpty(jsonString)) {
            return null;
        }
        if (classType == null) {
            throw new IllegalArgumentException("classType is null!");
        }
        try {
            CollectionType javaType = objectMapper.getTypeFactory().constructCollectionType(List.class, classType);
            return objectMapper.readValue(jsonString, javaType);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException(e);
        }
    }

    public static List<Object> toList(String jsonString) {
        return toList(jsonString, Object.class);
    }

    /**
     * Object类型的对象转为List集合
     *
     * @param object    当前对象
     * @param classType List的泛型
     * @return List<T>
     */
    public static <T> List<T> toList(Object object, Class<T> classType) {
        if (object == null || isEmpty(object.toString())) {
            return null;
        }
        if (classType == null) {
            throw new IllegalArgumentException("classType is null!");
        }
        try {
            CollectionType javaType = objectMapper.getTypeFactory().constructCollectionType(List.class, classType);
            if (object instanceof String) {
                return objectMapper.readValue((String) object, javaType);
            }
            return objectMapper.readValue(toJSONString(object), javaType);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException(e);
        }
    }

    public static List<Object> toList(Object object) {
        return toList(object, Object.class);
    }

    /**
     * JSON数组字符串反序列化为泛型为<Map<K,V>的List集合
     *
     * @param jsonArrayString JSON数组字符串
     * @param keyType         Map的Key类型
     * @param valueType       Map的Value类型
     * @return List<Map < K, V>>
     */
    public static <K, V> List<Map<K, V>> toMapList(String jsonArrayString, Class<K> keyType, Class<V> valueType) {
        if (isEmpty(jsonArrayString)) {
            return null;
        }
        if (keyType == null || valueType == null) {
            throw new IllegalArgumentException("keyType or valueType is null!");
        }
        try {
            TypeFactory typeFactory = objectMapper.getTypeFactory();
            MapType mapType = typeFactory.constructMapType(Map.class, keyType, valueType);
            CollectionType collectionType = typeFactory.constructCollectionType(List.class, mapType);
            return objectMapper.readValue(jsonArrayString, collectionType);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException(e);
        }
    }

    public static List<Map<String, Object>> toMapList(String jsonArrayString) {
        return toMapList(jsonArrayString, String.class, Object.class);
    }

    /**
     * Object类型的对象转为泛型为<Map<K,V>的List集合
     *
     * @param object    当前对象
     * @param keyType   Map的Key类型
     * @param valueType Map的Value类型
     * @return List<Map < K, V>>
     */
    public static <K, V> List<Map<K, V>> toMapList(Object object, Class<K> keyType, Class<V> valueType) {
        if (object == null || isEmpty(object.toString())) {
            return null;
        }
        if (keyType == null || valueType == null) {
            throw new IllegalArgumentException("keyType or valueType is null!");
        }
        try {
            TypeFactory typeFactory = objectMapper.getTypeFactory();
            MapType mapType = typeFactory.constructMapType(Map.class, keyType, valueType);
            CollectionType collectionType = objectMapper.getTypeFactory().constructCollectionType(List.class, mapType);
            if (object instanceof String) {
                return objectMapper.readValue((String) object, collectionType);
            }
            return objectMapper.readValue(toJSONString(object), collectionType);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException(e);
        }
    }

    public static List<Map<String, Object>> toMapList(Object object) {
        return toMapList(object, String.class, Object.class);
    }
    
   /**
     * JSON字符串转换为JSON
     *
     * @param jsonString JSON对象字符串
     * @return JsonNode
     */
    public static JsonNode toJSON(String jsonString) {
        if (isEmpty(jsonString)) {
            return null;
        }
        try {
            return objectMapper.readTree(jsonString);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException(e);
        }
    }

    /**
     * JSON字符串转换为JSON对象
     *
     * @param jsonString JSON对象字符串
     * @return ObjectNode
     */
    public static ObjectNode parseJSONObject(String jsonString) {
        if (isEmpty(jsonString)) {
            return null;
        }
        try {
            return (ObjectNode) objectMapper.readTree(jsonString);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException(e);
        }
    }

    /**
     * Object类型转换为JSON对象
     *
     * @param object 当前对象
     * @return ObjectNode
     */
    public static ObjectNode parseJSONObject(Object object) {
        if (object == null || isEmpty(object.toString())) {
            return null;
        }
        try {
            if (ObjectNode.class.isAssignableFrom(object.getClass())) {
                return (ObjectNode) object;
            }
            if (object instanceof String) {
                return (ObjectNode) objectMapper.readTree((String) object);
            }
            return (ObjectNode) objectMapper.readTree(toJSONString(object));
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException(e);
        }
    }

    /**
     * JSON字符串转换为JSON数组
     *
     * @param jsonString JSON数组字符串
     * @return ArrayNode
     */
    public static ArrayNode parseJSONArray(String jsonString) {
        if (isEmpty(jsonString)) {
            return newJSONArray();
        }
        try {
            return (ArrayNode) objectMapper.readTree(jsonString);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException(e);
        }
    }

    /**
     * Object类型转换为JSON数组
     *
     * @param object 当前对象
     * @return ArrayNode
     */
    public static ArrayNode parseJSONArray(Object object) {
        if (object == null || isEmpty(object.toString())) {
            return null;
        }
        try {
            if (ArrayNode.class.isAssignableFrom(object.getClass())) {
                return (ArrayNode) object;
            }
            if (object instanceof String) {
                return (ArrayNode) objectMapper.readTree((String) object);
            }
            return (ArrayNode) objectMapper.readTree(toJSONString(object));
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException(e);
        }
    }

    //============================================== 获取value值方法封装 =============================================================

    /**
     * 获取JSON对象 ObjectNode
     *
     * @param jsonNode json对象
     * @param key      JSON key
     * @return ObjectNode
     */
    public static ObjectNode getJSONObject(JsonNode jsonNode, String key) {
        if (jsonNode == null) {
            return null;
        }
        return (ObjectNode) Optional.ofNullable(jsonNode.get(key)).orElse(null);
    }

    /**
     * 获取JSON数组 ArrayNode
     *
     * @param jsonNode json对象
     * @param key      JSON key
     * @return ArrayNode
     */
    public static ArrayNode getJSONArray(JsonNode jsonNode, String key) {
        if (jsonNode == null) {
            return null;
        }
        return (ArrayNode) Optional.ofNullable(jsonNode.get(key)).orElse(null);
    }

    /**
     * 获取String类型的value
     *
     * @param jsonNode     json对象
     * @param key          JSON key
     * @param defaultValue 默认value
     * @return String
     */
    public static String getString(JsonNode jsonNode, String key, String defaultValue) {
        if (jsonNode == null) {
            return null;
        }
        return Optional.ofNullable(jsonNode.get(key)).filter(x -> !x.isNull()).map(JacksonUtil::getJsonNodeString).orElse(defaultValue);
    }

    public static String getString(JsonNode jsonNode, String key) {
        return getString(jsonNode, key, null);
    }

    /**
     * 获取Byte类型的value
     *
     * @param jsonNode     json对象
     * @param key          JSON key
     * @param defaultValue 默认value
     * @return Byte
     */
    public static Byte getByte(JsonNode jsonNode, String key, Byte defaultValue) {
        if (jsonNode == null) {
            return null;
        }
        return Optional.ofNullable(jsonNode.get(key)).filter(x -> !x.isNull()).map(x -> Byte.valueOf(getJsonNodeString(x))).orElse(defaultValue);
    }

    public static Byte getByte(JsonNode jsonNode, String key) {
        return getByte(jsonNode, key, null);
    }

    /**
     * 获取Short类型的value
     *
     * @param jsonNode     json对象
     * @param key          JSON key
     * @param defaultValue 默认value
     * @return Short
     */
    public static Short getShort(JsonNode jsonNode, String key, Short defaultValue) {
        if (jsonNode == null) {
            return null;
        }
        return Optional.ofNullable(jsonNode.get(key)).filter(x -> !x.isNull()).filter(x -> !x.isNull()).map(x -> Short.valueOf(getJsonNodeString(x))).orElse(defaultValue);
    }

    public static Short getShort(JsonNode jsonNode, String key) {
        return getShort(jsonNode, key, null);
    }

    /**
     * 获取Integer类型的value
     *
     * @param jsonNode     json对象
     * @param key          JSON key
     * @param defaultValue 默认value
     * @return Integer
     */
    public static Integer getInteger(JsonNode jsonNode, String key, Integer defaultValue) {
        if (jsonNode == null) {
            return null;
        }
        return Optional.ofNullable(jsonNode.get(key)).filter(x -> !x.isNull()).map(x -> Integer.valueOf(getJsonNodeString(x))).orElse(defaultValue);
    }

    public static Integer getInteger(JsonNode jsonNode, String key) {
        return getInteger(jsonNode, key, null);
    }

    /**
     * 获取Long类型的value
     *
     * @param jsonNode     json对象
     * @param key          JSON key
     * @param defaultValue 默认value
     * @return Long
     */
    public static Long getLong(JsonNode jsonNode, String key, Long defaultValue) {
        if (jsonNode == null) {
            return null;
        }
        return Optional.ofNullable(jsonNode.get(key)).filter(x -> !x.isNull()).map(x -> Long.valueOf(getJsonNodeString(x))).orElse(defaultValue);
    }

    public static Long getLong(JsonNode jsonNode, String key) {
        return getLong(jsonNode, key, null);
    }

    /**
     * 获取Double类型的value
     *
     * @param jsonNode     json对象
     * @param key          JSON key
     * @param defaultValue 默认value
     * @return Double
     */
    public static Double getDouble(JsonNode jsonNode, String key, Double defaultValue) {
        if (jsonNode == null) {
            return null;
        }
        return Optional.ofNullable(jsonNode.get(key)).filter(x -> !x.isNull()).map(x -> Double.valueOf(getJsonNodeString(x))).orElse(defaultValue);
    }

    public static Double getDouble(JsonNode jsonNode, String key) {
        return getDouble(jsonNode, key, null);
    }

    /**
     * 获取Boolean类型的value
     *
     * @param jsonNode     json对象
     * @param key          JSON key
     * @param defaultValue 默认value
     * @return boolean
     */
    public static boolean getBoolean(JsonNode jsonNode, String key, boolean defaultValue) {
        if (jsonNode == null) {
            return false;
        }
        return Optional.ofNullable(jsonNode.get(key)).filter(x -> !x.isNull()).map(x -> Boolean.valueOf(getJsonNodeString(x))).orElse(defaultValue);
    }

    public static boolean getBoolean(JsonNode jsonNode, String key) {
        return getBoolean(jsonNode, key, false);
    }

    /**
     * 获取Date类型的value
     *
     * @param jsonNode json对象
     * @param key      JSON key
     * @param format   日期格式对象
     * @return Date
     */
    public static Date getDate(JsonNode jsonNode, String key, SimpleDateFormat format) {
        if (jsonNode == null || format == null) {
            return null;
        }
        String dateStr = Optional.ofNullable(jsonNode.get(key)).filter(x -> !x.isNull()).map(JacksonUtil::getJsonNodeString).orElse(null);
        if (dateStr == null) {
            return null;
        }
        try {
            return format.parse(dateStr);
        } catch (ParseException e) {
            throw new IllegalArgumentException(e);
        }
    }

    public static Date getDate(JsonNode jsonNode, String key) {
        return getDate(jsonNode, key, formatLocal.get());
    }

    //============================================== 创建JSON对象/JSON数组 方法封装 =============================================================

    /**
     * 创建一个JSON对象
     *
     * @return ObjectNode
     */
    public static ObjectNode newJSONObject() {
        return objectMapper.createObjectNode();
    }

    /**
     * 创建一个JSON数组
     *
     * @return ArrayNode
     */
    public static ArrayNode newJSONArray() {
        return objectMapper.createArrayNode();
    }

   /**
     * 判断JSON属性个数是否为0
     *
     * @param jsonNode JsonNode
     * @return boolean
     */
    public static boolean isEmpty(JsonNode jsonNode) {
        return jsonNode == null || jsonNode.size() == 0;
    }
	public static boolean isNotEmpty(JsonNode jsonNode) {
        return !isEmpty(jsonNode);
    }
    /**
     * 判断字符串是否为null或者空字符串
     *
     * @param jsonString 字符串
     * @return boolean
     */
    private static boolean isEmpty(String jsonString) {
        return jsonString == null || jsonString.trim().length() <= 0;
    }

    /**
     * 去掉JsonNode toString后字符串的两端的双引号(直接用JsonNode的toString方法获取到的值做后续处理,Jackson去获取String类型的方法有坑)
     * @param jsonNode JsonNode
     * @return String
     */
    private static String getJsonNodeString(JsonNode jsonNode){
        if(jsonNode==null){
            return null;
        }
        //去掉字符串左右的引号
        String quotesLeft="^[\"]";
        String quotesRight="[\"]$";
        return jsonNode.toString().replaceAll(quotesLeft,"").replaceAll(quotesRight,"");
    }
}

3.测试实体类

package test.entity;

import com.fasterxml.jackson.annotation.JsonFormat;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

/**
 * @author lzq 2020/10/29
 */
public class Person {
    // 正常case
    private String name;
    // 空对象case
    private Integer age;
    // 日期转换case
    @JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd HH:mm")
    private Date date;
    // 默认值case
    private int height;

    private LocalDate localDate;
    private LocalDateTime localDateTime;
    private LocalTime localTime;

    private Info info;
    private List<String> list;
    private Map<String,Object> map;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public LocalDate getLocalDate() {
        return localDate;
    }

    public void setLocalDate(LocalDate localDate) {
        this.localDate = localDate;
    }

    public LocalDateTime getLocalDateTime() {
        return localDateTime;
    }

    public void setLocalDateTime(LocalDateTime localDateTime) {
        this.localDateTime = localDateTime;
    }

    public LocalTime getLocalTime() {
        return localTime;
    }

    public void setLocalTime(LocalTime localTime) {
        this.localTime = localTime;
    }

    public Info getInfo() {
        return info;
    }

    public void setInfo(Info info) {
        this.info = info;
    }

    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    public Map<String, Object> getMap() {
        return map;
    }

    public void setMap(Map<String, Object> map) {
        this.map = map;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", date=" + date +
                ", height=" + height +
                ", localDate=" + localDate +
                ", localDateTime=" + localDateTime +
                ", localTime=" + localTime +
                ", info=" + info +
                ", list=" + list +
                ", map=" + map +
                '}';
    }

    public static class Info{
        private String city;
        private String address;
        private int[] nums;
        private HashMap<String,Object> extension;

        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        public int[] getNums() {
            return nums;
        }

        public void setNums(int[] nums) {
            this.nums = nums;
        }

        public HashMap<String, Object> getExtension() {
            return extension;
        }

        public void setExtension(HashMap<String, Object> extension) {
            this.extension = extension;
        }

        @Override
        public String toString() {
            return "Info{" +
                    "city='" + city + '\'' +
                    ", address='" + address + '\'' +
                    ", nums=" + Arrays.toString(nums) +
                    ", extension=" + extension +
                    '}';
        }
    }
}

public class ZhangSan extends Person {
    private String zhangsanName;

    public String getZhangsanName() {
        return zhangsanName;
    }
    public void setZhangsanName(String zhangsanName) {
        this.zhangsanName = zhangsanName;
    }
}

4.测试类

package test.jackson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.counter.util.JacksonUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.junit.Assert;
import org.junit.Test;
import test.jackson.entity.AnXuanOrder;
import test.jackson.entity.Person;
import test.jackson.entity.Person.Info;
import test.jackson.entity.ZhangSan;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

/**
 * @author 2020/10/29
 */
public class JacksonUtilTest {

    @Test
    public void toJSONString() {
        // 造数据
        Person person = new Person();
        person.setName("Tom");
        person.setAge(40);
        person.setDate(new Date());
        person.setLocalDate(LocalDate.now());
        person.setLocalDateTime(LocalDateTime.now());
        person.setLocalTime(LocalTime.now());

        //System.out.println(JacksonUtil.toJSONString(person));
        //System.out.println(JacksonUtil.toPrettyJSONString(person));

        // 造数据
        List<Person> list = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            person = new Person();
            person.setName("Tom");
            person.setAge(new Random().nextInt(100));
            person.setDate(new Date());
            person.setLocalDate(LocalDate.now());
            person.setLocalDateTime(LocalDateTime.now());
            person.setLocalTime(LocalTime.now());
            list.add(person);
        }
        System.out.println("List序列化");
        //System.out.println(JacksonUtil.toPrettyJSONString(list));


    }

    @Test
    public void toJavaObject() {
        String json = "{\n" +
                "  \"name\" : \"Tom\",\n" +
                "  \"age\" : 40,\n" +
                "  \"date\" : \"2020-10-29 16:24\",\n" +
                "  \"height\" : 0,\n" +
                "  \"url\" : \"https://www.baidu.com?aaa=666&rrr=6\",\n" +
                "  \"localDate\" : \"2020-10-29\",\n" +
                "  \"localDateTime\" : \"2020-10-29 16:24:29\",\n" +
                "  \"localTime\" : \"16:24:29\"\n" +
                "}";
        System.out.println(JacksonUtil.parseJSONObject(json));
        //System.out.println(JacksonUtil.toJavaObject(json, Person.class));
        //System.out.println(JacksonUtil.toJavaObject(JacksonUtil.toJavaObject(json, Person.class), Person.class));
        //System.out.println(JacksonUtil.toJavaObject(JacksonUtil.toMap(json), Person.class));
    }

    @Test
    public void toMap() {
        String json = "{\n" +
                "  \"name\" : \"Tom\",\n" +
                "  \"age\" : 40,\n" +
                "  \"date\" : \"2020-10-29 16:24\",\n" +
                "  \"height\" : 0,\n" +
                "  \"localDate\" : \"2020-10-29\",\n" +
                "  \"localDateTime\" : \"2020-10-29 16:24:29\",\n" +
                "  \"localTime\" : \"16:24:29\"\n" +
                "}";
        Map<String, Object> map1 = JacksonUtil.toMap(json);
        System.out.println(map1);
        String json2 = "{\n" +
                "  \"name\":\"张三\",\n" +
                "  \"job\":\"罪犯\"\n" +
                "}";
        Map<String, String> map2 = JacksonUtil.toMap(json2, String.class, String.class);
        System.out.println(map2);
        String json3 = "{\n" +
                "  \"age\":99,\n" +
                "  \"height\":0.09\n" +
                "}";
        Map<String, Double> map3 = JacksonUtil.toMap(json3, String.class, Double.class);
        System.out.println(map3);

    }

    @Test
    public void toList() {
        String json = "[ {\n" +
                "  \"name\" : \"Tom\",\n" +
                "  \"age\" : 55,\n" +
                "  \"date\" : \"2020-10-29 16:36\",\n" +
                "  \"height\" : 0,\n" +
                "  \"localDate\" : \"2020-10-29\",\n" +
                "  \"localDateTime\" : \"2020-10-29 16:36:45\",\n" +
                "  \"localTime\" : \"16:36:45\"\n" +
                "}, {\n" +
                "  \"name\" : \"Tom\",\n" +
                "  \"age\" : 75,\n" +
                "  \"date\" : \"2020-10-29 16:36\",\n" +
                "  \"height\" : 0,\n" +
                "  \"localDate\" : \"2020-10-29\",\n" +
                "  \"localDateTime\" : \"2020-10-29 16:36:45\",\n" +
                "  \"localTime\" : \"16:36:45\"\n" +
                "}, {\n" +
                "  \"name\" : \"Tom\",\n" +
                "  \"age\" : 6,\n" +
                "  \"date\" : \"2020-10-29 16:36\",\n" +
                "  \"height\" : 0,\n" +
                "  \"localDate\" : \"2020-10-29\",\n" +
                "  \"localDateTime\" : \"2020-10-29 16:36:45\",\n" +
                "  \"localTime\" : \"16:36:45\"\n" +
                "} ]";
        List<Object> list1 = JacksonUtil.toList(json);
        System.out.println(list1);
        System.out.println("=================================================");
        List<Person> list2 = JacksonUtil.toList(json, Person.class);
        System.out.println(list2);
    }


    @Test
    public void parseObjectNode() {
        String json = "{\n" +
                "  \"name\":\"张三\",\n" +
                "  \"job\":\"罪犯\",\n" +
                "  \"body\":{\n" +
                "\t\"age\":99,\n" +
                "\t\"height\":0.09\n" +
                "  },\n" +
                "  \"bir\":\"2020-10-29 12:03:56\",\n" +
                "  \"nums\":[1,2,5,6,8,9],\n" +
                "  \"extension\":[\n" +
                "    {\n" +
                "\t \"city\":\"北京\",\n" +
                "\t \"address\":\"朝阳区\"\n" +
                "\t},\n" +
                "\t{ \n" +
                "\t \"city\":\"天津\",\n" +
                "\t \"address\":\"北辰区\"\n" +
                "\t}\n" +
                "  ]\n" +
                "}";
        ObjectNode jsonNode = JacksonUtil.parseJSONObject(json);
        System.out.println(jsonNode.toPrettyString());
        System.out.println(JacksonUtil.getJSONArray(jsonNode,"extension"));
        Object a = json;
        System.out.println(JacksonUtil.parseJSONObject(a));
    }

    @Test
    public void parseArrayNode() {
        String json = "[\n" +
                "    {\n" +
                "\t \"city\":\"北京\",\n" +
                "\t \"address\":\"朝阳区\"\n" +
                "\t},\n" +
                "\t{ \n" +
                "\t \"city\":\"天津\",\n" +
                "\t \"address\":\"北辰区\"\n" +
                "\t}\n" +
                "  ]";
        ArrayNode jsonNodes = JacksonUtil.parseJSONArray(json);
        System.out.println(jsonNodes.toPrettyString());
        System.out.println("===============================");
        for (JsonNode jsonNode : jsonNodes) {
            System.out.println(jsonNode);
        }
    }

    @Test
    public void getObjectNode() {
        String json = "{\n" +
                "  \"name\":\"张三\",\n" +
                "  \"job\":\"罪犯\",\n" +
                "  \"body\":{\n" +
                "\t\"age\":99,\n" +
                "\t\"height\":0.09\n" +
                "  },\n" +
                "  \"bir\":\"2020-10-29 12:03:56\",\n" +
                "  \"nums\":[1,2,5,6,8,9],\n" +
                "  \"extension\":[\n" +
                "    {\n" +
                "\t \"city\":\"北京\",\n" +
                "\t \"address\":\"朝阳区\"\n" +
                "\t},\n" +
                "\t{ \n" +
                "\t \"city\":\"天津\",\n" +
                "\t \"address\":\"北辰区\"\n" +
                "\t}\n" +
                "  ]\n" +
                "}";
        ObjectNode jsonNode = JacksonUtil.parseJSONObject(json);
        System.out.println(JacksonUtil.getJSONObject(jsonNode, "body"));
    }

    @Test
    public void getArrayNode() {
        String json = "{\n" +
                "  \"name\":\"张三\",\n" +
                "  \"job\":\"罪犯\",\n" +
                "  \"body\":{\n" +
                "\t\"age\":99,\n" +
                "\t\"height\":0.09\n" +
                "  },\n" +
                "  \"bir\":\"2020-10-29 12:03:56\",\n" +
                "  \"nums\":[1,2,5,6,8,9],\n" +
                "  \"extension\":[\n" +
                "    {\n" +
                "\t \"city\":\"北京\",\n" +
                "\t \"address\":\"朝阳区\"\n" +
                "\t},\n" +
                "\t{ \n" +
                "\t \"city\":\"天津\",\n" +
                "\t \"address\":\"北辰区\"\n" +
                "\t}\n" +
                "  ]\n" +
                "}";
        ObjectNode jsonNode = JacksonUtil.parseJSONObject(json);
        System.out.println(JacksonUtil.getJSONArray(jsonNode, "extension"));
        System.out.println(JacksonUtil.getJSONArray(jsonNode, "nums"));
    }

    @Test
    public void getString() {
        String json = "\n" +
                "{\n" +
                "  \"name\":\"张三\",\n" +
                "  \"job\":\"罪犯\",\n" +
                "  \"bir\":\"2020-10-29 12:03:56\",\n" +
                "  \"nums\":[1,2,5,6,8,9],\n" +
                "  \"flagStr\":\"true\",\n" +
                "  \"flag\":true,\n" +
                "  \"ageStr\":\"99\",\n" +
                "  \"age\":99,\n" +
                "  \"heightStr\":\"5.09\",\n" +
                "  \"height\":5.09\n" +
                "\n" +
                "}";
        ObjectNode jsonNode = JacksonUtil.parseJSONObject(json);
        System.out.println(JacksonUtil.getString(jsonNode, "name"));
        System.out.println(JacksonUtil.getString(jsonNode, "name1"));
        System.out.println(JacksonUtil.getString(jsonNode, "name1", "默认"));
        System.out.println(JacksonUtil.getString(jsonNode, "age"));
        System.out.println(JacksonUtil.getString(jsonNode, "bir"));
        System.out.println(JacksonUtil.getString(jsonNode, "height"));

    }


    @Test
    public void getByte() {
        String json = "\n" +
                "{\n" +
                "  \"flagStr\":\"true\",\n" +
                "  \"flag\":true,\n" +
                "  \"ageStr\":\"99\",\n" +
                "  \"age\":99,\n" +
                "  \"age1\":127,\n" +
                "  \"heightStr\":\"5.09\",\n" +
                "  \"height\":5.09\n" +
                "\n" +
                "}";
        ObjectNode jsonNode = JacksonUtil.parseJSONObject(json);
        System.out.println(JacksonUtil.getByte(jsonNode, "age"));
        System.out.println(JacksonUtil.getByte(jsonNode, "ageStr"));
        System.out.println(JacksonUtil.getByte(jsonNode, "age1"));
    }

    @Test
    public void getShort() {
        String json = "\n" +
                "{\n" +
                "  \"flagStr\":\"true\",\n" +
                "  \"flag\":true,\n" +
                "  \"ageStr\":\"99\",\n" +
                "  \"age\":99,\n" +
                "  \"heightStr\":\"5.09\",\n" +
                "  \"height\":5.09\n" +
                "\n" +
                "}";
        ObjectNode jsonNode = JacksonUtil.parseJSONObject(json);
        System.out.println(JacksonUtil.getShort(jsonNode, "age"));
        System.out.println(JacksonUtil.getShort(jsonNode, "ageStr"));
    }

    @Test
    public void getInteger() {
        String json = "\n" +
                "{\n" +
                "  \"flagStr\":\"true\",\n" +
                "  \"flag\":true,\n" +
                "  \"ageStr\":\"99\",\n" +
                "  \"age\":99,\n" +
                "  \"heightStr\":\"5.09\",\n" +
                "  \"height\":5.09\n" +
                "\n" +
                "}";
        ObjectNode jsonNode = JacksonUtil.parseJSONObject(json);
        System.out.println(JacksonUtil.getInteger(jsonNode, "age"));
        System.out.println(JacksonUtil.getInteger(jsonNode, "ageStr"));
    }

    @Test
    public void getLong() {
        String json = "\n" +
                "{\n" +
                "  \"flagStr\":\"true\",\n" +
                "  \"flag\":true,\n" +
                "  \"ageStr\":\"99\",\n" +
                "  \"age\":99,\n" +
                "  \"heightStr\":\"5.09\",\n" +
                "  \"height\":5.09\n" +
                "\n" +
                "}";
        ObjectNode jsonNode = JacksonUtil.parseJSONObject(json);
        System.out.println(JacksonUtil.getInteger(jsonNode, "age"));
        System.out.println(JacksonUtil.getInteger(jsonNode, "ageStr"));
    }

    @Test
    public void getDouble() {
        String json = "\n" +
                "{\n" +
                "  \"flagStr\":\"true\",\n" +
                "  \"flag\":true,\n" +
                "  \"ageStr\":\"99\",\n" +
                "  \"age\":99,\n" +
                "  \"heightStr\":\"5.09\",\n" +
                "  \"height\":5.09\n" +
                "\n" +
                "}";
        ObjectNode jsonNode = JacksonUtil.parseJSONObject(json);
        System.out.println(JacksonUtil.getDouble(jsonNode, "age"));
        System.out.println(JacksonUtil.getDouble(jsonNode, "ageStr"));
        System.out.println(JacksonUtil.getDouble(jsonNode, "heightStr"));
        System.out.println(JacksonUtil.getDouble(jsonNode, "height"));
    }


    @Test
    public void getBoolean() {
        String json = "\n" +
                "{\n" +
                "  \"flagStr\":\"true\",\n" +
                "  \"flag\":true,\n" +
                "  \"ageStr\":\"99\",\n" +
                "  \"age\":99,\n" +
                "  \"heightStr\":\"5.09\",\n" +
                "  \"height\":5.09\n" +
                "\n" +
                "}";
        ObjectNode jsonNode = JacksonUtil.parseJSONObject(json);
        System.out.println(JacksonUtil.getBoolean(jsonNode, "age"));
        System.out.println(JacksonUtil.getBoolean(jsonNode, "ageStr"));
        System.out.println(JacksonUtil.getBoolean(jsonNode, "heightStr"));
        System.out.println(JacksonUtil.getBoolean(jsonNode, "height"));
        System.out.println(JacksonUtil.getBoolean(jsonNode, "flagStr"));
        System.out.println(JacksonUtil.getBoolean(jsonNode, "flag"));
        Assert.assertTrue(JacksonUtil.getBoolean(jsonNode, "flag"));
    }


    @Test
    public void getDate() {
        String json = "\n" +
                "{\n" +
                "  \"name\":\"张三\",\n" +
                "  \"job\":\"罪犯\",\n" +
                "  \"bir\":\"2020-10-29 12:03:56\",\n" +
                "  \"flagStr\":\"true\",\n" +
                "  \"flag\":true,\n" +
                "  \"ageStr\":\"99\",\n" +
                "  \"age\":99,\n" +
                "  \"heightStr\":\"5.09\",\n" +
                "  \"height\":5.09\n" +
                "\n" +
                "}";
        ObjectNode jsonNode = JacksonUtil.parseJSONObject(json);
        System.out.println(JacksonUtil.getDate(jsonNode, "bir"));
        System.out.println(JacksonUtil.getDate(jsonNode, "bir", new SimpleDateFormat("yyyy-MM-dd HH:mm")));
        System.out.println(JacksonUtil.getDate(jsonNode, "bir", new SimpleDateFormat("yyyy-MM-dd HH")));
    }


    @Test
    public void newObjectNode() {
        ObjectNode jsonNodes = JacksonUtil.newJSONObject();
        jsonNodes.put("name", "张三丰");
        jsonNodes.put("age", "111");
        System.out.println(jsonNodes);
        jsonNodes.remove("age");
        System.out.println(jsonNodes);
    }

    @Test
    public void newArrayNode() {
        ArrayNode jsonNodes = JacksonUtil.newJSONArray();
        ObjectNode jsonNode = JacksonUtil.newJSONObject();
        jsonNode.put("name", "张三丰");
        jsonNode.put("age", "111");
        jsonNodes.add(jsonNode);
        System.out.println(jsonNodes);
        System.out.println(JacksonUtil.toPrettyJSONString(jsonNodes));
        System.out.println(JacksonUtil.toJSONString(jsonNodes));
    }

    /**
     * 复杂对象测试
     */
    @Test
    public void complexObjTest() {
        // 造数据
        Person person = new Person();
        person.setName("Tom");
        person.setAge(40);
        person.setHeight(888);
        person.setDate(new Date());
        person.setLocalDate(LocalDate.now());
        person.setLocalDateTime(LocalDateTime.now());
        person.setLocalTime(LocalTime.now());
        person.setList(Lists.newArrayList("list1", "list2", "list3"));
        person.setMap(ImmutableMap.of("key1", "value1", "key2", "value2", "key3", "value3"));
        Person.Info info = new Person.Info();
        info.setCity("北京");
        info.setAddress("朝阳区");
        info.setNums(new int[]{3, 5, 77, 99999, 0});
        info.setExtension(new HashMap<>(ImmutableMap.of("k1", "v1", "k2", "v2", "k3", "v3")));
        person.setInfo(info);

        String json = JacksonUtil.toPrettyJSONString(person);
        System.out.println(json);

        System.out.println(JacksonUtil.parseJSONObject(json));
        Person person1 = JacksonUtil.toJavaObject(json, Person.class);
        System.out.println(person1);
    }

    @Test
    public void test6() {
        System.out.println(JacksonUtil.toJSONString("979dfs8g|\n\n4s6df" +
                "*6///**/tderdgfsfds ggsr dgfssq$@#@@#%$^fe"));
        System.out.println(JacksonUtil.toJSONString(11));
        ESBMessage esbMessage = new ESBMessage();
        esbMessage.setReConsumeTimes((byte) 0);
        esbMessage.setVersion((byte) 0);
        esbMessage.setTotalLen(0);
        esbMessage.setSubject(0);
        esbMessage.setMessageID(0L);
        esbMessage.setMessageType((byte) 0);
        esbMessage.setDeliveryMode((byte) 0);
        esbMessage.setClientID(0);
        esbMessage.setBody(new byte[]{11});
        esbMessage.setSessionID(0L);
        esbMessage.setProtocolType((byte) 0);
        esbMessage.setNeedReplay((byte) 0);
        esbMessage.setCommandType((byte) 0);
        esbMessage.setIp(0);
        esbMessage.setTimestamp(0L);
        esbMessage.setSequenceId(0);
        esbMessage.setSequenceKey(new Object());
        esbMessage.setDelayLevel(0);
        esbMessage.setDelaySeconds(0L);
        esbMessage.setESBKey("");
        esbMessage.setProperties("");
        esbMessage.setPropertiesMap(Maps.newHashMap());
        esbMessage.setPropertiesLen(0);
        esbMessage.setBodyLen(0);
        esbMessage.setLogicOffset(0L);
        esbMessage.setPullVersion(0L);
        esbMessage.setTag("");
        esbMessage.setStrictOrder(false);
        esbMessage.setStarttime(0L);
        esbMessage.setWaitSendTmp1(0L);
        esbMessage.setAfterSendTmp2(0L);
        esbMessage.setReceiveAckTmp3(0L);

        System.out.println(JacksonUtil.toPrettyJSONString(esbMessage));
    }

    @Test
    public void test7() {
        ObjectNode jsonNode = JacksonUtil.newJSONObject();
        // ObjectNode jsonNode = new ObjectNode(JsonNodeFactory.withExactBigDecimals(true));
        jsonNode.put("aa", BigDecimal.valueOf(1000000000000L));
        System.out.println(jsonNode.toPrettyString());
    }


    @Test
    public void test8() {
        String json = "{\n" +
                "\t\"unityLocals\": \"1162,1162\",\n" +
                "\t\"localType\": 2,\n" +
                "\t\"unityCityId\": 37,\n" +
                "\t\"xiaoquId\": 100430655,\n" +
                "\t\"addDate\": 1520603180000,\n" +
                "\t\"bianHao\": \"\",\n" +
                "\t\"casLock\": 0,\n" +
                "\t\"cateId\": 13,\n" +
                "\t\"brokerId\": 11111,\n" +
                "\t\"chaoXiang\": 2,\n" +
                "\t\"contactName\": \"苏中闰\",\n" +
                "\t\"effectiveDate\": 1552139180563,\n" +
                "\t\"houseId\": 735654988077056,\n" +
                "\t\"jiaGe\": \"880000\",\n" +
                "\t\"jiageDanwei\": 0,\n" +
                "\t\"mianJi\": \"147.0\",\n" +
                "\t\"params\": {\n" +
                "\t\t\"22\": \"0\",\n" +
                "\t\t\"88\": \"4\",\n" +
                "\t\t\"89\": \"2389\",\n" +
                "\t\t\"24\": \"1\",\n" +
                "\t\t\"25\": \"2\"\n" +
                "\t},\n" +
                "\n" +
                "\t\"phone\": \"18716365076\",\n" +
                "\t\"postDate\": 1520603180000,\n" +
                "\t\"shi\": 3,\n" +
                "\t\"source\": 17,\n" +
                "\t\"state\": 5,\n" +
 
                "\t\"stateAjk\": 0,\n" +
                "\t\"suoZaiLouCeng\": 15,\n" +
                "\t\"ting\": 2,\n" +
                "\t\"title\": \"急售!!陈家坪华宇花园三房147平 才88万 拎包入住\",\n" +
                "\t\"userIP\": \"10.126.92.95\",\n" +
                "\t\"userId\": 4453615,\n" +
                "\t\"userIdAjk\": 4453615,\n" +
                "\t\"wei\": 2,\n" +
                "\t\"xiangXiDiZhi\": \"南华街810号\",\n" +
                "\t\"zhuangXiuQingKuang\": 4,\n" +
                "\t\"zongLouCeng\": 30,\n" +
                "\n" +
                "\t\"msgSendTime\": 1555918430958,\n" +
                "\t\"system\": \"\",\n" +
                "\t\"fromIp\": \"100\",\n" +
                "\t\"callerKey\": \"******dsfdsdfsfsdf\",\n" +
                "\t\"isBiz\": 1,\n" +
                "\t\"isVip\": 1,\n" +
                "\t\"webSite\": [1, 2],\n" +
                "\t\"userId\": 44429517666583,\n" +
                "\t\"sortId\": 103527,\n" +
                "\t\"picList\": [{\n" +
                "\t\t\"host\": \"1\",\n" +
                "\t\t\"hash\": \"36fe930c068a57f066e5445153494d14\",\n" +
                "\t\t\"width\": 931,\n" +
                "\t\t\"size\": 146747,\n" +
                "\t\t\"category\": 1,\n" +
                "\t\t\"height\": 912,\n" +
                "\t\t\"order\": 0,\n" +
                "\t\t\"isCover\": 1,\n" +
                "\t\t\"fullPath\": \"http://pic1.ajkimg.com/display/anjuke/36fe930c068a57f066e5445153494d14/600x600.jpg\",\n" +
                "\t\t\"addTime\": 1546329618\n" +
                "\t}, {\n" +
                "\t\t\"host\": \"1\",\n" +
                "\t\t\"hash\": \"7093bdcc322fd774e3f56284be933513\",\n" +
                "\t\t\"width\": 1242,\n" +
                "\t\t\"size\": 125422,\n" +
                "\t\t\"category\": 1,\n" +
                "\t\t\"height\": 640,\n" +
                "\t\t\"order\": 1,\n" +
                "\t\t\"isCover\": 0,\n" +
                "\t\t\"fullPath\": \"http://pic1.ajkimg.com/display/anjuke/7093bdcc322fd774e3f56284be933513/600x600.jpg\",\n" +
                "\t\t\"addTime\": 1546329618\n" +
                "\t}]\n" +
                "\n" +
                "}";

        ObjectNode jsonNodes = JacksonUtil.parseJSONObject(json);
        //System.out.println(jsonNodes);
        // System.out.println(JacksonUtil.toPrettyJSONString(jsonNodes));
        System.out.println(JacksonUtil.toMap(JSON.parseObject(json)));
        System.out.println(JacksonUtil.toJSONString("55555张三"));
    }

    @Test
    public void test9() {
        AnXuanOrder anXuanOrder = new AnXuanOrder();
        anXuanOrder.setAddTime(new Timestamp(System.currentTimeMillis()));
        anXuanOrder.setBizCode(0);
        anXuanOrder.setOrderId(0L);
        anXuanOrder.setSign("");
        anXuanOrder.setStartTime("");
        anXuanOrder.setEndTime("");
        anXuanOrder.setPpu("");
        anXuanOrder.setStatus(0);

        System.out.println(JacksonUtil.toPrettyJSONString(anXuanOrder));

    }

    @Test
    public void test10() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", 2);
        jsonObject.put("age", 5);

        System.out.println(JacksonUtil.toPrettyJSONString(jsonObject));

        ZhangSan zhangSan = new ZhangSan();
        zhangSan.setZhangsanName("88888888");
        zhangSan.setName("99999999");
        zhangSan.setAge(0);
        zhangSan.setDate(new Date());
        zhangSan.setHeight(0);
        zhangSan.setLocalDate(LocalDate.now());
        zhangSan.setLocalDateTime(LocalDateTime.now());
        zhangSan.setLocalTime(LocalTime.now());
        zhangSan.setInfo(new Info());
        zhangSan.setList(Lists.newArrayList());
        zhangSan.setMap(Maps.newHashMap());
        System.out.println(JacksonUtil.toPrettyJSONString(zhangSan));
    }

    @Test
    public void test11() {
        List<Person> list = Lists.newArrayList();
        Person person1 = new Person();
        person1.setName("Tom");
        person1.setAge(40);
        person1.setDate(new Date());
        person1.setLocalDate(LocalDate.now());
        person1.setLocalDateTime(LocalDateTime.now());
        person1.setLocalTime(LocalTime.now());

        Person person2 = new Person();
        person2.setName("张飞");
        person2.setAge(99);
        person2.setDate(new Date());
        person2.setLocalDate(LocalDate.now());
        person2.setLocalDateTime(LocalDateTime.now());
        person2.setLocalTime(LocalTime.now());

        list.add(person1);
        list.add(person2);

        List<Map<String, Object>> maps = JacksonUtil.toMapList(list, String.class, Object.class);

        for (Map<String, Object> map : maps) {
            map.forEach((key,value)-> System.out.println(key+"->"+value));
        }

    }

    @Test
    public void test12(){
        Object json="[ {\n" +
                "  \"name\" : \"Tom\",\n" +
                "  \"age\" : 40,\n" +
                "  \"date\" : \"2020-12-05 17:12\",\n" +
                "  \"height\" : 0,\n" +
                "  \"localDate\" : \"2020-12-05\",\n" +
                "  \"localDateTime\" : \"2020-12-05 17:12:45\",\n" +
                "  \"localTime\" : \"17:12:45\"\n" +
                "}, {\n" +
                "  \"name\" : \"张飞\",\n" +
                "  \"age\" : 99,\n" +
                "  \"date\" : \"2020-12-05 17:12\",\n" +
                "  \"height\" : 0,\n" +
                "  \"localDate\" : \"2020-12-05\",\n" +
                "  \"localDateTime\" : \"2020-12-05 17:12:45\",\n" +
                "  \"localTime\" : \"17:12:45\"\n" +
                "} ]";
        List<Map<String, Object>> maps = JacksonUtil.toMapList(json, String.class, Object.class);
        System.out.println(JacksonUtil.toPrettyJSONString(maps));

        List<Map<String, Object>> maps1 = JacksonUtil.toMapList(maps);
        System.out.println(JacksonUtil.toPrettyJSONString(maps1));
    }

    @Test
    public void test13(){
        String json="{\"attributes\":\"6\",\"message\":\"接口转发异常:500 \",\"result\":[{\"aaa\":444}],\"result1\":{\"aaa\":444,\"bbb\":\"bbb\"},\"status\":\"error\",\"date\":\"2020-12-05 17:12\"}";
        ObjectNode jsonObject = JacksonUtil.parseJSONObject(json);
        System.out.println(JacksonUtil.getString(jsonObject,"result"));
        System.out.println(JacksonUtil.getString(jsonObject,"result1"));
       // String attributes = JacksonUtil.getString(jsonObject,"attributes");

        //Map<String, Object> am = JacksonUtil.toMap(attributes);
        //System.out.println(am);

        System.out.println(JacksonUtil.getBoolean(jsonObject, "attributes"));
        System.out.println(JacksonUtil.getInteger(jsonObject, "attributes"));
        System.out.println(JacksonUtil.getDouble(jsonObject, "attributes"));
        System.out.println(JacksonUtil.getByte(jsonObject, "attributes"));
        System.out.println(JacksonUtil.getLong(jsonObject, "attributes"));
        //System.out.println(JacksonUtil.getDate(jsonObject, "attributes"));
        System.out.println(JacksonUtil.getDate(jsonObject, "date",new SimpleDateFormat("yyyy-MM-dd HH:mm")));
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值