1. @JsonIgnore 作用是 json序列化时Bean中的属性会被忽略。
2. @JsonFormat 作用是json序列化时格式化Bean中的属性输出的格式(如:Date)
3.@JsonSerialize 作用是json序列化时按照自己定义的格式方法执行。
如:
package com.boce.test;
import java.io.Serializable;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.ibm.icu.util.Calendar;
public class Person implements Serializable {
private String name;
@JsonIgnore
private String sex;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date birday;
@JsonSerialize(using=DoubleFormat.class)
private Double weight;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirday() {
return birday;
}
public void setBirday(Date birday) {
this.birday = birday;
}
public Double getWeight() {
return weight;
}
public void setWeight(Double weight) {
this.weight = weight;
}
public static void main(String[] args) {
Person p = new Person();
p.setName("boce");
p.setSex("man");
p.setBirday(Calendar.getInstance().getTime());
p.setWeight(150.2);
String result ="";
ObjectMapper mapper = new ObjectMapper();
// 配置mapper忽略空属性
mapper.setSerializationInclusion(Include.NON_EMPTY);
// 默认情况,Jackson使用Java属性字段名称作为 Json的属性名称,也可以使用Jackson
try {
result = mapper.writeValueAsString(p);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
System.out.println(result);
}
}
格式化double 数据为 ###.00 ,有两位有效数字.
package com.boce.test;
import java.io.IOException;
import java.text.DecimalFormat;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
/**
* double 数据格式化为 ****.00;
* @author dell
*
*/
public class DoubleFormat extends JsonSerializer<Double>{
DecimalFormat df = new DecimalFormat("###.00");
@Override
public void serialize(Double value, JsonGenerator gen, SerializerProvider serializers)
throws IOException, JsonProcessingException {
if(value !=null){
gen.writeString(df.format(value));
}
}
}
输出结果:
{"name":"boce","birday":"2017-02-22 03:16:01","weight":"150.20"}
说明:sex 没有在json字符串中出现。
birday,weight 已经被格式化