json----fastjson的使用,jackson的使用


教程地址

一、简介

官网:https://www.json.org/json-zh.html

二、使用场景

  • 网络传输

    描述同样的信息,JSON相比xml占用更少的空间。

    <?xml version="1.0" encoding="UTF-8"?>
    <person>
    	<id>1</id>
      <name>张三</name>
      <age>30</age>
    </person>
    

    json表示:

    {
      "id":1,
      "name":"张三",
      "age":30
    }
    
  • 序列化存储

三、java里操作JSON有哪些技术?

  • 所谓的操作

    把java里面的bean、map、collection等转为json字符串(序列化)或反向操作(反序列化)。

  • java里面操作json的技术一览

image-20220817122950571

四、fastjson

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.2.73</version>
</dependency>

4.1 序列化

快速入门

实体类创建

@Data
public class Person {
    /**
     * 用户ID
     */
    private Long id;
    private String name;
    private String pwd;
    /**
     * 地址
     */
    private String addr;
    /**
     * 网站
     */
    private String websiteUrl;
    private Date registerDate;
    private LocalDateTime birthDay;
}

测试类

@Test
public void test01() {
    Person person = new Person();
    person.setId(0L);
    person.setName("张三");
    person.setPwd("1234");
    person.setAddr("北京");
    person.setWebsiteUrl("www.zhangsan.com");
    person.setRegisterDate(new Date());
    person.setBirthDay(LocalDateTime.now());

    String jsonstr = JSON.toJSONString(person);
    System.out.println(jsonstr);
}

测试结果

{"addr":"北京","birthDay":"2022-08-23T23:51:51.634","id":0,"name":"张三","pwd":"1234","registerDate":1661269911525,"websiteUrl":"www.zhangsan.com"}

问题:

  1. 任意属性为空时,序列化后会被忽略
  2. Date日期格式不是想要的
  3. LocalDateTime格式也不是想要的

序列化的枚举介绍

SerializerFeature 枚举常量,做序列化的个性需求,是可变参数

SerializerFeature.WriteMapNullValue : 序列化时包含null的值

SerializerFeature.WriteNullNumberAsZero : 枚举的常量,序列化自动为值为null,序列化为0

SerializerFeature.WriteNullBooleanAsFalse : 枚举常量,序列化,布尔值为null,序列化为false

SerializerFeature.WriteDateUseDateFormat : 枚举常量,序列化,日期的格式化 , 后面可以在字段注解中处理

SerializerFeature.PrettyFormat :枚举常量,序列化,美化输出,美化输出也有另一种,会在后面介绍 String jsonstr = JSON.toJSONString(list,true);

入门中的问题

1.如何包含null的字段
    @Test
    public void test02() {
        Person person = new Person();
        person.setId(0L);
        person.setName("张三");
//        person.setPwd("1234");
        person.setAddr("北京");
        person.setWebsiteUrl("www.zhangsan.com");
        person.setRegisterDate(new Date());
        person.setBirthDay(LocalDateTime.now());

        /*
        WriteMapNullValue:指定序列化时包含null
         */
        String jsonstr = JSON.toJSONString(person,SerializerFeature.WriteMapNullValue);
        System.out.println(jsonstr);
    }
{"addr":"北京","birthDay":"2022-08-23T23:57:10.589","id":0,"name":"张三","pwd":null,"registerDate":1661270230399,"websiteUrl":"www.zhangsan.com"}
2.日期格式化
@Data
public class Person {
  
		//略...
    
    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    private Date registerDate;
    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime birthDay;
}
{"addr":"北京","birthDay":"2022-08-24 00:01:04","id":0,"name":"张三","pwd":"1234","registerDate":"2022-08-24 00:01:04","websiteUrl":"www.zhangsan.com"}

{"addr":"北京","birthDay":"2022-08-24 00:01:28","id":0,"name":"张三","pwd":null,"registerDate":"2022-08-24 00:01:28","websiteUrl":"www.zhangsan.com"}
3.$ref

引用探测

@Test
public void test03() {
    List<Person> list = new ArrayList<>();
    Person person = new Person();
    person.setId(0L);
    person.setName("张三");
    person.setAddr("北京");
    person.setWebsiteUrl("www.zhangsan.com");
    list.add(person);
    list.add(person);
    list.add(person);

    String jsonstr = JSON.toJSONString(list);
    System.out.println(jsonstr);
}
[{"addr":"北京","id":0,"name":"张三","websiteUrl":"www.zhangsan.com"},{"$ref":"$[0]"},{"$ref":"$[0]"}]

禁用引用探测

@Test
public void test04() {
    List<Person> list = new ArrayList<>();
    Person person = new Person();
    person.setId(0L);
    person.setName("张三");
    person.setAddr("北京");
    person.setWebsiteUrl("www.zhangsan.com");
    list.add(person);
    list.add(person);
    list.add(person);

    String jsonstr = JSON.toJSONString(list,SerializerFeature.DisableCircularReferenceDetect);
    System.out.println(jsonstr);
}
[{"addr":"北京","id":0,"name":"张三","websiteUrl":"www.zhangsan.com"},{"addr":"北京","id":0,"name":"张三","websiteUrl":"www.zhangsan.com"},{"addr":"北京","id":0,"name":"张三","websiteUrl":"www.zhangsan.com"}]

可以指定多个序列化器

@Test
public void test04() {
    List<Person> list = new ArrayList<>();
    Person person = new Person();
    person.setId(0L);
    person.setName("张三");
    person.setAddr("北京");
    person.setWebsiteUrl("www.zhangsan.com");
    list.add(person);
    list.add(person);
    list.add(person);

    String jsonstr = JSON.toJSONString(list,SerializerFeature.DisableCircularReferenceDetect,SerializerFeature.WriteMapNullValue);
    System.out.println(jsonstr);
}
[{"addr":"北京","birthDay":null,"id":0,"name":"张三","pwd":null,"registerDate":null,"websiteUrl":"www.zhangsan.com"},{"addr":"北京","birthDay":null,"id":0,"name":"张三","pwd":null,"registerDate":null,"websiteUrl":"www.zhangsan.com"},{"addr":"北京","birthDay":null,"id":0,"name":"张三","pwd":null,"registerDate":null,"websiteUrl":"www.zhangsan.com"}]
4.SerializeFilter定制处理

对属性或属性值在序列化前做定制化处理

    @Test
    public void test05() {
        Person person = new Person();
        person.setId(0L);
        person.setName("张三");
//        person.setPwd("1234");
        person.setAddr("北京");
        person.setWebsiteUrl("www.zhangsan.com");
        person.setRegisterDate(new Date());
        person.setBirthDay(LocalDateTime.now());

        /*
        object: person对象
        name: 属性
        value: name属性对应的值
         */
        NameFilter nameFilter = (object,name,value) -> name.toUpperCase();
        String jsonstr = JSON.toJSONString(person,nameFilter);
        System.out.println(jsonstr);
    }
{"ADDR":"北京","BIRTHDAY":"2022-08-24T00:17:13.472","ID":0,"NAME":"张三","REGISTERDATE":1661271433376,"WEBSITEURL":"www.zhangsan.com"}
5.美化格式输出
//美化格式输出
String str = JSON.toJSONString(obj,true);
@Test
public void test08() {
    List<Person> list = new ArrayList<>();
    Person person = new Person();
    person.setId(0L);
    person.setName("张三");
    person.setAddr("北京");
    person.setWebsiteUrl("www.zhangsan.com");
    list.add(person);
    list.add(person);
    list.add(person);

    String jsonstr = JSON.toJSONString(list,true);
    System.out.println(jsonstr);
}
[
	{
		"addr":"北京",
		"id":0,
		"name":"张三",
		"websiteUrl":"www.zhangsan.com"
	},
	{"$ref":"$[0]"},
	{"$ref":"$[0]"}
]

4.2 反序列化

简单使用

@Test
public void test06() {
    String str = "{\"addr\":\"北京\",\"birthDay\":\"2022-08-24 00:01:28\",\"id\":0,\"name\":\"张三\",\"pwd\":null,\"registerDate\":\"2022-08-24 00:01:28\",\"websiteUrl\":\"www.zhangsan.com\"}";
    Person person = JSON.parseObject(str, Person.class);
    System.out.println(person);
}
Person(id=0, name=张三, pwd=null, addr=北京, websiteUrl=www.zhangsan.com, registerDate=Wed Aug 24 00:01:28 CST 2022, birthDay=2022-08-24T00:01:28)

泛型返回

@Data
public class ResultVO<T> {

    private Boolean success = Boolean.TRUE;
    private T data;
    private ResultVO() {}

    public static <T> ResultVO<T> buildSuccess(T t) {
        ResultVO<T> resultVO = new ResultVO<>();
        resultVO.setData(t);
        return resultVO;
    }
}
    @Test
    public void test07() {
        String str = "{\"addr\":\"北京\",\"birthDay\":\"2022-08-24 00:01:28\",\"id\":0,\"name\":\"张三\",\"pwd\":null,\"registerDate\":\"2022-08-24 00:01:28\",\"websiteUrl\":\"www.zhangsan.com\"}";
        Person person = JSON.parseObject(str, Person.class);

        //返回调用端resultvo
        ResultVO<Person> personResultVO = ResultVO.buildSuccess(person);
        String voJsonStr = JSON.toJSONString(personResultVO);


        //窎远端吧voJsonStr反序列化为对象
        //反序列化后不能够获取到泛型类型
//        ResultVO resultVO = JSON.parseObject(voJsonStr, ResultVO.class);
//        System.out.println(resultVO);
//        Object data = resultVO.getData();

        ResultVO<Person> deSerializedVo = JSON.parseObject(voJsonStr, new TypeReference<ResultVO<Person>>(){});
        System.out.println(deSerializedVo);
        Person data = deSerializedVo.getData();
        System.out.println(data);
    }
ResultVO(success=true, data=Person(id=0, name=张三, pwd=null, addr=北京, websiteUrl=www.zhangsan.com, registerDate=Wed Aug 24 00:01:28 CST 2022, birthDay=2022-08-24T00:01:28))
Person(id=0, name=张三, pwd=null, addr=北京, websiteUrl=www.zhangsan.com, registerDate=Wed Aug 24 00:01:28 CST 2022, birthDay=2022-08-24T00:01:28)

fastjson 对JSON中存在,实体类中不存在的key默认的处理就是忽略处理

4.3 通用配置

1. 指定属性名和JSON key的对应关系

@JSONField(name = "userName")
private String name;


//序列化时忽略某字段,参考
https://www.cnblogs.com/pcheng/p/11507901.html

2. 忽略序列化某字段

@JSONField(serialize = false,deserialize = false)
private String pwd;

4.4 注解介绍

@JSonField注解

该注解作用域方法上,字段上,参数上。 可在序列化和反序列化时进行特性功能定制

  • 注解属性:name 【序列化|反序列化】 的名字

  • 注解属性:ordinal 【序列化】后的顺序 ,值越小,顺序越靠前

  • 注解属性:format 【序列化|反序列化】 的日期格式

  • 注解属性:serialize 【序列化】是否序列化该字段

  • 注解属性:deserialize 【反序列化】是否反序列化该字段

  • 注解属性:serialzeFeatures 【序列化】序列化时的特性定义

@JSONType注解

该注解作用域类上,对该类的字段进行序列化和反序列化时的特性功能定制

  • 注解属性:includes 要被序列化的字段,如includes = {"id","name","add"}
  • 注解属性:orders 要被序列化的字段的顺序,如orders = {"name","age","add","id"}

4.5 spring 中将springmvc的JSON工具换成fastjson

image-20220902232128481

4.6 springboot中使用fastjson

spring.http.converters.preferred-json-mapper=fastjson
@Bean
    public HttpMessageConverters fastJsonHttpMessageConverters(){
        //1、先定义一个convert转换消息的对象
        FastJsonHttpMessageConverter fastConverter=new FastJsonHttpMessageConverter();
        //2、添加fastjson的配置信息,比如是否要格式化返回的json数据;
        FastJsonConfig fastJsonConfig=new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        //附加:处理中文乱码
        List<MediaType> fastMedisTypes = new ArrayList<MediaType>();
        fastMedisTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(fastMedisTypes);
        //3、在convert中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);
        HttpMessageConverter<?> converter=fastConverter;
        return new HttpMessageConverters(converter);
    }

五、jackson

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
</dependency>
<!--对LocalDateTime等jdk8时间日期api的转换支持-->
<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
import lombok.Data;

import java.time.LocalDateTime;
import java.util.Date;

@Data
public class Person {
    private Long id;
    private String name;
    private String pwd;

    private String addr;

    private String websiteUrl;
    private Date registerDate;
    private LocalDateTime birthDay;
}

5.1 序列化

快速入门

@Test
public void test01() throws JsonProcessingException {
    Person person = new Person();
    person.setId(0L);
    person.setName("张三");
    person.setAddr("北京");
    person.setWebsiteUrl("www.zhangsan.com");
    person.setRegisterDate(new Date());
    person.setBirthDay(LocalDateTime.now());

    String jsonStr = new ObjectMapper().writeValueAsString(person);
    System.out.println(jsonStr);
}

{“id”:0,“name”:“张三”,“pwd”:null,“addr”:“北京”,“websiteUrl”:“www.zhangsan.com”,“registerDate”:1662122499126,“birthDay”:{“year”:2022,“month”:“SEPTEMBER”,“dayOfMonth”:2,“dayOfWeek”:“FRIDAY”,“dayOfYear”:245,“monthValue”:9,“hour”:20,“minute”:41,“second”:39,“nano”:206000000,“chronology”:{“calendarType”:“iso8601”,“id”:“ISO”}}}

配置序列化时只包含非空属性(全局配置)

    private static ObjectMapper objectMapper = new ObjectMapper();
    static {
        //配置序列化时只包含非空属性
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }


    @Test
    public void test02() throws JsonProcessingException {
        Person person = new Person();
        person.setId(0L);
        person.setName("张三");
        person.setAddr("北京");
        person.setWebsiteUrl("www.zhangsan.com");
        person.setRegisterDate(new Date());
        person.setBirthDay(LocalDateTime.now());

        String jsonStr =objectMapper.writeValueAsString(person);
        System.out.println(jsonStr);
    }

{“id”:0,“name”:“张三”,“addr”:“北京”,“websiteUrl”:“www.zhangsan.com”,“registerDate”:1662122675845,“birthDay”:{“hour”:20,“minute”:44,“second”:35,“nano”:901000000,“dayOfYear”:245,“dayOfWeek”:“FRIDAY”,“month”:“SEPTEMBER”,“dayOfMonth”:2,“year”:2022,“monthValue”:9,“chronology”:{“id”:“ISO”,“calendarType”:“iso8601”}}}

配置序列化时只包含非空属性(单个bean配置)

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Person {

时间格式化配置(单个bean配置)

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Person {
    private Long id;
    private String name;
    private String pwd;

    private String addr;

    private String websiteUrl;
  	//时间格式化配置
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    private Date registerDate;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    private LocalDateTime birthDay;
}

{“id”:0,“name”:“张三”,“addr”:“北京”,“websiteUrl”:“www.zhangsan.com”,“registerDate”:“2022-09-02 20:51:21”,“birthDay”:{“dayOfYear”:245,“dayOfWeek”:“FRIDAY”,“month”:“SEPTEMBER”,“dayOfMonth”:2,“year”:2022,“monthValue”:9,“hour”:20,“minute”:51,“second”:21,“nano”:87000000,“chronology”:{“id”:“ISO”,“calendarType”:“iso8601”}}}

这里注意没有格式化LocaDateTime

<!--对LocalDateTime等jdk8时间日期api的转换支持-->
<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
private static ObjectMapper objectMapper = new ObjectMapper();
static {
    //配置序列化时只包含非空属性
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    // 自动通过spi发现Jackson的module并注册
    objectMapper.findAndRegisterModules();
}

{“id”:0,“name”:“张三”,“addr”:“北京”,“websiteUrl”:“www.zhangsan.com”,“registerDate”:“2022-09-02 20:55:28”,“birthDay”:“2022-09-02 20:55:28”}

image-20220902211536171

时间格式化配置(全局配置)

private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static ObjectMapper objectMapper = new ObjectMapper();
static {
    //配置序列化时只包含非空属性
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    // 自动通过spi发现Jackson的module并注册
    // objectMapper.findAndRegisterModules();


    //全局配置LocalDateTime的格式
    //手动配置javaTimeModule并注册
    JavaTimeModule javaTimeModule = new JavaTimeModule();
    javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)));
    javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)));
    //注册
    objectMapper.registerModule(javaTimeModule);
}

image-20220902212613280

美化输出

//美化输出
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);

{
“id” : 0,
“name” : “张三”,
“addr” : “北京”,
“websiteUrl” : “www.zhangsan.com”,
“registerDate” : “2022-09-02 21:28:04”,
“birthDay” : “2022-09-02 21:28:05”
}

5.2 反序列化

简单使用

@Test
public void test03() throws IOException {
    String jsonstr = "    {\n" +
            "        \"id\" : 0,\n" +
            "            \"name\" : \"张三\",\n" +
            "            \"addr\" : \"北京\",\n" +
            "            \"websiteUrl\" : \"www.zhangsan.com\",\n" +
            "            \"registerDate\" : \"2022-09-02 21:28:04\",\n" +
            "            \"birthDay\" : \"2022-09-02 21:28:05\"\n" +
            "    }";

    Person person = objectMapper.readValue(jsonstr, Person.class);
    System.out.println(person);
}

JSON中存在实体类不存在的key

@Test
public void test03() throws IOException {
    String jsonstr = "    {\n" +
            "        \"id\" : 0,\n" +
            "            \"name\" : \"张三\",\n" +
            //添加实体类中不存在的属性
            "            \"age\" : \"18\",\n" +
            "            \"addr\" : \"北京\",\n" +
            "            \"websiteUrl\" : \"www.zhangsan.com\",\n" +
            "            \"registerDate\" : \"2022-09-02 21:28:04\",\n" +
            "            \"birthDay\" : \"2022-09-02 21:28:05\"\n" +
            "    }";

    Person person = objectMapper.readValue(jsonstr, Person.class);
    System.out.println(person);
}

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field “age” (class com.zs.utilsTest.jackson.Person), not marked as ignorable (7 known properties: “addr”, “websiteUrl”, “id”, “pwd”, “registerDate”, “name”, “birthDay”])
at [Source: (String)" {
“id” : 0,
“name” : “张三”,
“age” : “18”,
“addr” : “北京”,
“websiteUrl” : “www.zhangsan.com”,
“registerDate” : “2022-09-02 21:28:04”,
“birthDay” : “2022-09-02 21:28:05”
}"; line: 4, column: 22] (through reference chain: com.zs.utilsTest.jackson.Person[“age”])

需要添加配置

//忽略JSON串中的key在实体类中不存在的key
//objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

对于泛型的处理

@Test
public void test05() throws IOException {
    Person person = new Person();
    person.setId(0L);
    person.setName("aaa");
    person.setPwd("");
    person.setAddr("");
    person.setWebsiteUrl("");
    person.setRegisterDate(new Date());
    person.setBirthDay(LocalDateTime.now());

    ResultVO<Person> personResultVO = ResultVO.buildSuccess(person);
    String personJson = objectMapper.writeValueAsString(personResultVO);

    ResultVO<Person> resultVO = objectMapper.readValue(personJson, new TypeReference<ResultVO<Person>>() {
    });

    System.out.println(resultVO.getData());
}

5.3 通用配置

序列化:驼峰转下划线,反序列化:下划线转驼峰

//驼峰转下划线
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);

指定属性和json字符串key对应关系

@JsonProperty("address")
private String addr;

忽略指定属性

@JsonIgnore
private String pwd;

其他应用

对象更新

对象更新:对象的合并/重写,如果后者有值用后者,否则前者的值不变

@Test
public void test06() throws IOException {
    Person person = new Person();
    person.setId(0L);
    person.setName("aaa");
    person.setAddr("上海");

    Person person2 = new Person();
    person2.setId(2L);
    person2.setAddr("北京");
    person2.setRegisterDate(new Date());

    Person updatePerson = objectMapper.updateValue(person,person2);
    System.out.println(updatePerson);
}

Person(id=2, name=aaa, pwd=null, addr=北京, websiteUrl=null, registerDate=Fri Sep 02 22:07:58 CST 2022, birthDay=null)

所有文件

package com.zs.utilsTest.jackson;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonInclude;
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.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;

import com.zs.utilsTest.json.domain.ResultVO;
import org.junit.Test;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class JacksonTest {
    private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    private static ObjectMapper objectMapper = new ObjectMapper();
    static {
        //配置序列化时只包含非空属性
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        // 自动通过spi发现Jackson的module并注册
        // objectMapper.findAndRegisterModules();

        // 对Date进行配置,SimpleDateFormat是线程不安全的
        objectMapper.setDateFormat(new SimpleDateFormat(DATE_TIME_FORMAT));

        //全局配置LocalDateTime的格式
        //手动配置javaTimeModule并注册
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)));
        //注册
        objectMapper.registerModule(javaTimeModule);


        //美化输出
        objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);

        //忽略JSON串中的key在实体类中不存在的key
        //objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);


        //驼峰转下划线
        objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
    }


    @Test
    public void test06() throws IOException {
        Person person = new Person();
        person.setId(0L);
        person.setName("aaa");
        person.setAddr("上海");

        Person person2 = new Person();
        person2.setId(2L);
        person2.setAddr("北京");
        person2.setRegisterDate(new Date());

        Person updatePerson = objectMapper.updateValue(person,person2);
        System.out.println(updatePerson);
    }


    @Test
    public void test05() throws IOException {
        Person person = new Person();
        person.setId(0L);
        person.setName("aaa");
        person.setPwd("");
        person.setAddr("");
        person.setWebsiteUrl("");
        person.setRegisterDate(new Date());
        person.setBirthDay(LocalDateTime.now());

        ResultVO<Person> personResultVO = ResultVO.buildSuccess(person);
        String personJson = objectMapper.writeValueAsString(personResultVO);

        ResultVO<Person> resultVO = objectMapper.readValue(personJson, new TypeReference<ResultVO<Person>>() {
        });

        System.out.println(resultVO.getData());
    }


    @Test
    public void test04() throws IOException {
        String jsonstr = "    {\n" +
                "        \"id\" : 0,\n" +
                "            \"name\" : \"张三\",\n" +
                //添加实体类中不存在的属性
                "            \"age\" : \"18\",\n" +
                "            \"addr\" : \"北京\",\n" +
                "            \"websiteUrl\" : \"www.zhangsan.com\",\n" +
                "            \"registerDate\" : \"2022-09-02 21:28:04\",\n" +
                "            \"birthDay\" : \"2022-09-02 21:28:05\"\n" +
                "    }";

        Person person = objectMapper.readValue(jsonstr, Person.class);
        System.out.println(person);
    }

    @Test
    public void test03() throws IOException {
        String jsonstr = "    {\n" +
                "        \"id\" : 0,\n" +
                "            \"name\" : \"张三\",\n" +
                //添加实体类中不存在的属性
                "            \"age\" : \"18\",\n" +
                "            \"addr\" : \"北京\",\n" +
                "            \"websiteUrl\" : \"www.zhangsan.com\",\n" +
                "            \"registerDate\" : \"2022-09-02 21:28:04\",\n" +
                "            \"birthDay\" : \"2022-09-02 21:28:05\"\n" +
                "    }";

        Person person = objectMapper.readValue(jsonstr, Person.class);
        System.out.println(person);
    }



    @Test
    public void test02() throws JsonProcessingException {
        Person person = new Person();
        person.setId(0L);
        person.setName("张三");
        person.setAddr("北京");
        person.setWebsiteUrl("www.zhangsan.com");
        person.setRegisterDate(new Date());
        person.setBirthDay(LocalDateTime.now());

        String jsonStr =objectMapper.writeValueAsString(person);
        System.out.println(jsonStr);
    }



    @Test
    public void test01() throws JsonProcessingException {
        Person person = new Person();
        person.setId(0L);
        person.setName("张三");
        person.setAddr("北京");
        person.setWebsiteUrl("www.zhangsan.com");
        person.setRegisterDate(new Date());
        person.setBirthDay(LocalDateTime.now());

        String jsonStr = new ObjectMapper().writeValueAsString(person);
        System.out.println(jsonStr);
    }




}
package com.zs.utilsTest.jackson;


import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

import java.time.LocalDateTime;
import java.util.Date;

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Person {
    private Long id;
    private String name;
    @JsonIgnore
    private String pwd;

    @JsonProperty("address")
    private String addr;

    private String websiteUrl;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    private Date registerDate;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    private LocalDateTime birthDay;
}
package com.zs.utilsTest.json.domain;

import com.sun.org.apache.xpath.internal.operations.Bool;
import com.zs.domain.Result;
import lombok.Data;


@Data
public class ResultVO<T> {

    private Boolean success = Boolean.TRUE;
    private T data;
    private ResultVO() {}

    public static <T> ResultVO<T> buildSuccess(T t) {
        ResultVO<T> resultVO = new ResultVO<>();
        resultVO.setData(t);
        return resultVO;
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

悠闲的线程池

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值