标签:color type central new des stat one bsp 匹配
引用jar:jackson-core,jackson-databind,jackson-annotations
http://central.maven.org/maven2/com/fasterxml/jackson/core/jackson-core/2.9.9/jackson-core-2.9.9.jar
1、jackson基本使用
1.1、创建Person对象
public class Person { private String name; private Integer age; public Person(String name, Integer age) { this.name = name; this.age = age; } public String getName() { return name; } }
1.2、Main方法调用
备注:对象转json需要属性拥有get方法(注解方法除外)
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)); } }
输出结果为:
{"name":"jackson"}
2、注解使用
2.1、@JsonProperty注解使用
@JsonProperty注解类似于sql里字段的别名,用于序列化,使用注解字段属性,替代原字段属性
@JsonProperty("userName") private String name;
序列化结果为:在序列化的json串中,userName替代了name
{"userName":"jackson"}
2.2、@JsonIgnore注解使用
@JsonIgnore注解是在序列化时忽略该字段
@JsonIgnore @JsonProperty("userName") private String name; @JsonProperty("userAge") private Integer age;
序列化结果为:{"userAge":20}
{"userAge":20}
2.3、@JsonIgnoreProperties注解使用
2.3.1、序列化@JsonIgnoreProperties与@JsonIgnore类似,用于类上,注解使用的是字段别名
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(value={"name","userAge"}) public class Person { @JsonIgnore @JsonProperty("userName") private String name; @JsonProperty("userAge") private Integer age; @JsonProperty("userHeight") private Integer height; public Person(String name, Integer age, Integer height) { this.name = name; this.age = age; this.height = height; } }
ObjectMapper mapper = new ObjectMapper(); Person person = new Person("jackson",20,175); System.out.println(mapper.writeValueAsString(person));
运行结果为:{"userHeight":175}
{"userHeight":175}
2.3.2、@JsonIgnoreProperties(ignoreUnknown = true)用于忽略字段不匹配情况,相当于mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
备注:反序列化需要有无参构造器
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).getHeight());
2.4、@JsonTypeName @JsonTypeInfo
@JsonTypeName(value = "user")
@JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME)
在序列化是增加一层
序列化结果为:{"user":{"height":175}}
{"user":{"height":175}}
2.5、@JsonRootName注解
2.4组合等于类上注解@JsonRootName("user") 和 mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
2.6、@JsonFormat注解格式化日期格式
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss:SSS",timezone="GMT+8")
private Date date;
标签:color type central new des stat one bsp 匹配
原文地址:https://www.cnblogs.com/miaosj/p/10936451.html