其他分享
首页 > 其他分享> > Jackson基础使用手册

Jackson基础使用手册

作者:互联网

1、对象转json字符串

import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
    public static void main(String[] arges) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        Person person = new Person("jackson",20);
        System.out.println(mapper.writeValueAsString(person));
    }
}

1.1、使用字段别名

  @JsonProperty("userName")
    private String name;

1.2、@JsonIgnore注解使用

@JsonIgnore注解是在序列化时忽略该字段

    @JsonIgnore
    @JsonProperty("userName")
    private String name;
    @JsonProperty("userAge")
    private Integer age;

1.3、@JsonFormat注解格式化日期格式

    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss:SSS",timezone="GMT+8")
    private Date date;

1.4、JavaType

1.4.1、如果为Map类型

mapper.getTypeFactory().constructParametricType(Map.class,String.class,Student.class);

第二个参数是Map的key,第三个参数是Map的value

1.4.2、如果为List类型

personList  =  mapper.readValue(mapper.writeValueAsString(personList),mapper.getTypeFactory().constructParametricType(List.class,Person.class));

1.5、TypeReference

TypeReference比javaType模式更加方便,代码也更加简洁

mapper.readValue(json, new TypeReference<List<Person>>(){}); 

2、json字符串转对象

ObjectMapper mapper = new ObjectMapper();
Person person = new Person("jackson",20,175);
System.out.println(mapper.writeValueAsString(person));
//mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
System.out.println(mapper.readValue("{\"sheight\":172}", Person.class));

 

标签:mapper,Jackson,String,基础,Person,使用手册,new,class,ObjectMapper
来源: https://www.cnblogs.com/qianxiaoPro/p/16218162.html