Java Jackson ObjectMapper-Annotations
屏蔽相关属性
- @JsonIgnore
/**
* Created by Jeffy on 16/5/17.
*/
public class Person {
@JsonIgnore
private String firstName;
private String lastName;
private String personId;
public String getFirstName() {
return firstName;
}
}
测试
/**
* Created by Jeffy on 16/5/17.
*/
public class JacksonAnnoMain {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
Person person = new Person();
person.setFirstName("Lee");
person.setLastName("jeffy");
person.setPersonId("009xhihis");
System.err.println(objectMapper.writeValueAsString(person));
}
}
输出
{"lastName":"jeffy","personId":"009xhihis"}
- @JsonIgnoreProperties
@JsonIgnoreProperties({"firstName","lastName"})
public class Person {
private String firstName;
private String lastName;
private String personId;
}
测试
/**
* Created by Jeffy on 16/5/17.
*/
public class JacksonAnnoMain {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
Person person = new Person();
person.setFirstName("Lee");
person.setLastName("jeffy");
person.setPersonId("009xhihis");
System.err.println(objectMapper.writeValueAsString(person));
}
}
输出
{"personId":"009xhihis"}
- @JsonIgnoreType
public class Person {
private String firstName;
private String lastName;
private String personId;
private Address address;
@JsonIgnoreType
public static class Address{
public String streetName = null;
public String houseNumber = null;
}
}
测试
/**
* Created by Jeffy on 16/5/17.
*/
public class JacksonAnnoMain {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
Person person = new Person();
person.setFirstName("Lee");
person.setLastName("jeffy");
person.setPersonId("009xhihis");
System.err.println(objectMapper.writeValueAsString(person));
}
}
输出
{"firstName":"Lee","lastName":"jeffy","personId":"009xhihis"}
可以看到@JsonIgnoreType 和 @JsonIgnore有相似功能
- @JsonAutoDetect
注释@JsonAutoDetect用于告诉Jackson在读取和写入对象时包括不公开的属性。 这是一个示范课程,向您展示如何使用@JsonAutoDetect注释:
import com.fasterxml.jackson.annotation.JsonAutoDetect;
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY )
public class PersonAutoDetect {
private long personId = 123;
public String name = null;
}
常量 有 ANY, DEFAULT, NON_PRIVATE, NONE, PROTECTED_AND_PRIVATE and PUBLIC_ONLY.
- @JsonSetter
解决setter方法和feild字段名称不一致导致的问题
public class Person {
private String firstName;
private String lastName;
private String personId;
private Address address;
public String getName() {
return firstName;
}
@JsonSetter("firstName")
public void setName(String firstName) {
this.firstName = firstName;
}
}
如果加上了注解 @JsonSetter("firstName")输出结果为:注意 firstName
{"lastName":"jeffy","personId":"009xhihis","firstName":"Lee"}
如果不加上了注解 @JsonSetter("firstName")输出结果为:注意 name
{"lastName":"jeffy","personId":"009xhihis","name":"Lee"}
- @JsonCreator
使用这个注解可以省略setter方法,使用构造函数
public class PersonImmutable {
private long id = 0;
private String name = null;
@JsonCreator
public PersonImmutable(
@JsonProperty("id") long id,
@JsonProperty("name") String name ) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
}
- @JacksonInject
使用这个注解是将json字符串中没有包含的字段映射到使用@JacksonInject的字段
demo
public class Person {
private String firstName;
private String lastName;
private String personId;
private Address address;
@JacksonInject
private String source;
...省略getters和setters
}
String tempJson = "{\"firstName\":\"Lee\",\"lastName\":\"jeffy\",\"personId\":\"009xhihis\"}";
InjectableValues inject = new InjectableValues.Std().addValue(String.class, "viashare.cn");
Person person2 = new ObjectMapper().reader(inject).forType(Person.class).readValue(tempJson);
System.err.println(person2.getSource());
System.err.println(person2.getFirstName());
输出
viashare.cn
Lee
注意如果是在Json中有source字段,如下,那么上面的代码在添加source映射时就不是viashare.cn 而是null。
{"firstName":"Lee","lastName":"jeffy","personId":"009xhihis","source":null}
- @JsonDeserialize
字段的转换,比如下面的代码,想要将对boolean字段进行转换,需要重写JsonDeserializer 中的方法 deserialize
public class PersonDeserialize {
public long id = 0;
public String name = null;
@JsonDeserialize(using = OptimizedBooleanDeserializer.class)
public boolean enabled = false;
}
public class OptimizedBooleanDeserializer
extends JsonDeserializer<Boolean> {
@Override
public Boolean deserialize(JsonParser jsonParser,
DeserializationContext deserializationContext) throws
IOException, JsonProcessingException {
String text = jsonParser.getText();
if("0".equals(text)) return false;
return true;
}
}
转换时的调用
PersonDeserialize person = objectMapper
.reader(PersonDeserialize.class)
.readValue(new File("data/person-optimized-boolean.json"));
- @JsonInclude
满足一定的条件在进行序列话成json
比如:
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class PersonInclude {
public long personId = 0;
public String name = null;
}
- @JsonGetter
替换属性名称
public class PersonGetter {
private long personId = 0;
@JsonGetter("id")
public long personId() { return this.personId; }
@JsonSetter("id")
public void personId(long personId) { this.personId = personId; }
}
输出
{"id":0}
@JsonAnyGetter
将Object中key-value映射到对象中平级的属性
public class Person {
private String firstName;
private String lastName;
private String personId;
private Address address;
private Map<String, Object> properties = new HashMap();
@JsonAnyGetter
public Map<String, Object> properties() {
return properties;
}
...省略其他字段的getter和setter
/**
* Created by Jeffy on 16/5/17.
*/
public class JacksonAnnoMain {
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
Person person = new Person();
person.setFirstName("Lee");
person.setLastName("jeffy");
person.setPersonId("009xhihis");
Map<String,Object> map = new HashMap();
map.put("classes","classes");
map.put("school","school");
person.setProperties(map);
String json = objectMapper.writeValueAsString(person);
System.err.println(json);
}
}
输出
{"firstName":"Lee","lastName":"jeffy","personId":"009xhihis","source":null,"school":"school","classes":"classes"}
- @JsonPropertyOrder
对字段进行排序
@JsonPropertyOrder({"name", "personId"})
public class PersonPropertyOrder {
public long personId = 0;
public String name = null;
}
- @JsonRawValue
如果字段中是一个json的字符串,在序列化的时候需要。
public class PersonRawValue {
public long personId = 0;
@JsonRawValue
public String address =
"{ \"street\" : \"Wall Street\", \"no\":1}";
}
有注解@JsonRawValue
{"personId":0,"address":{ "street" : "Wall Street", "no":1}}
没有注解@JsonRawValue
{"personId":0,"address":"{ \"street\" : \"Wall Street\", \"no\":1}"}
- @JsonValue
public class Person {
private String firstName;
private String lastName;
private String personId;
private Address address;
@JsonValue
public String toJson(){
return this.firstName+","+this.lastName;
}
}
测试代码
/**
* Created by Jeffy on 16/5/17.
*/
public class JacksonAnnoMain {
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
Person person = new Person();
person.setFirstName("Lee");
person.setLastName("jeffy");
person.setPersonId("009xhihis");
// Map<String,Object> map = new HashMap();
// map.put("classes","classes");
// map.put("school","school");
// person.setProperties(map);
String json = objectMapper.writeValueAsString(person);
System.err.println(json);
}
}
输出
"Lee,jeffy"
- @JsonSerialize
对字段的映射值进行转化
public class PersonSerializer {
public long personId = 0;
public String name = "John";
@JsonSerialize(using = OptimizedBooleanSerializer.class)
public boolean enabled = false;
}
public class OptimizedBooleanSerializer extends JsonSerializer<Boolean> {
@Override
public void serialize(Boolean aBoolean, JsonGenerator jsonGenerator,
SerializerProvider serializerProvider)
throws IOException, JsonProcessingException {
if(aBoolean){
jsonGenerator.writeNumber(1);
} else {
jsonGenerator.writeNumber(0);
}
}
}
网友评论