jackson在实际应用中给我们提供了一系列注解,提高了开发的灵活性,下面介绍一下最常用的一些注解

@JsonIgnoreProperties
此注解是类注解,作用是json序列化时将Java bean中的一些属性忽略掉,序列化和反序列化都受影响。

@JsonIgnore
此注解用于属性或者方法上(最好是属性上),作用和上面的@JsonIgnoreProperties一样。

@JsonFormat
此注解用于属性或者方法上(最好是属性上),可以方便的把Date类型直接转化为我们想要的模式,比如@JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss")

@JsonSerialize
此注解用于属性或者getter方法上,用于在序列化时嵌入我们自定义的代码,比如序列化一个double时在其后面限制两位小数点,将一个Date类型转化成指定类型字符串。

public class JsonDoubleSerialize extends JsonSerializer<Double> {

    private DecimalFormat df = new DecimalFormat("##.000");

    @Override
public void serialize(Double value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException { jgen.writeString(df.format(value));
}
}
/**
* 把Date类型序列化成指定合适的字符串
*/
public class JsonDateSerialize extends JsonSerializer<Date> {
@Override
public void serialize(Date date, JsonGenerator jgen,
SerializerProvider provider)
throws IOException, JsonProcessingException {
String formattedDate = "";
if (date != null) {
//把日期序列化成yyyy-MM-dd格式的字符串
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
formattedDate = simpleDateFormat.format(date);
}
jgen.writeString(formattedDate);
}
}

@JsonDeserialize
此注解用于属性或者setter方法上,用于在反序列化时可以嵌入我们自定义的代码,类似于上面的@JsonSerialize

/**
* 将一个字符串反序列化成一个Date类型
*/
public class JsonDateDeserialize extends JsonDeserializer<Date> { @Override
public Date deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
//拿到的是"yyyy-MM-dd"形式的字符串,现在要在json反序列化的时候转化成Date类型
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String date = jp.getText();
if (date == null || date.trim().length() == 0) {
return null;
}
try {
return format.parse(date);
} catch (Exception e) { }
return null;
}
}

完整例子

//表示序列化时忽略的属性
@JsonIgnoreProperties(value = {"word"})
public class Person {
private String name;
private int age;
private boolean sex;
@JsonSerialize(using = JsonDateSerialize.class)
@JsonDeserialize(using = JsonDateDeserialize.class)
private Date birthday;
private String word;
@JsonSerialize(using = JsonDoubleSerialize.class)
private double salary; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public boolean isSex() {
return sex;
} public void setSex(boolean sex) {
this.sex = sex;
} public Date getBirthday() {
return birthday;
} public void setBirthday(Date birthday) {
this.birthday = birthday;
} public String getWord() {
return word;
} public void setWord(String word) {
this.word = word;
} public double getSalary() {
return salary;
} public void setSalary(double salary) {
this.salary = salary;
} public Person(String name, int age) {
this.name = name;
this.age = age;
} public Person(String name, int age, boolean sex, Date birthday,
String word, double salary) {
super();
this.name = name;
this.age = age;
this.sex = sex;
this.birthday = birthday;
this.word = word;
this.salary = salary;
} public Person() {
} @Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", sex=" + sex
+ ", birthday=" + birthday + ", word=" + word + ", salary="
+ salary + "]";
} }
public class Demo {
public static void main(String[] args) { //writeJsonObject(); readJsonObject();
} // 直接写入一个对象(所谓序列化)
public static void writeJsonObject() {
ObjectMapper mapper = new ObjectMapper();
Person person = new Person("zhangsan", 25, true, new Date(), "coder",
2500.0);
try {
String string = mapper.writeValueAsString(person);
//{"name":"zhangsan","age":25,"sex":true,"birthday":"2016-12-03 22:02:23","salary":"2500.000"}
System.out.println(string);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} // 直接将一个json转化为对象(所谓反序列化)
public static void readJsonObject() {
ObjectMapper mapper = new ObjectMapper(); try {
String string = "{\"name\":\"zhangsan\",\"age\":25,\"sex\":true,\"birthday\":\"2016-12-03 22:02:23\",\"word\":\"coder\",\"salary\":\"2500.000\"}";
Person person = mapper.readValue(string, Person.class);
//Person [name=zhangsan, age=25, sex=true, birthday=Sat Dec 03 00:00:00 CST 2016, word=null, salary=2500.0]
System.out.println(person.toString());
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Jackson(使用注解)的更多相关文章

  1. jackson annotations注解详解

    jackson中常用到的注解 猛击下面的连接地址 http://blog.csdn.net/sdyy321/article/details/40298081

  2. jackson annotations注解详解 (zhuan)

    http://blog.csdn.net/sdyy321/article/details/40298081 ************************************** 官方WIKI: ...

  3. jackson基于注解的简单使用

    Jackson提供了一系列注解,方便对JSON序列化和反序列化进行控制,下面介绍一些常用的注解. 1.@JsonIgnore 此注解用于属性上,作用是进行JSON操作时忽略该属性. 2.@JsonFo ...

  4. jackson 常用注解,比如忽略某些属性,驼峰和下划线互转

    一般情况下使用JSON只使用了java对象与字符串的转换,但是,开发APP时候,我们经常使用实体类来做转换:这样,就需要用到注解: Jackson默认是针对get方法来生成JSON字符串的,可以使用注 ...

  5. Jackson /常用注解/ annotation(转)

    1.@JsonAutoDetect 自动检测,(作用在类上)来开启/禁止自动检测. fieldVisibility:字段的可见级别 ANY:任何级别的字段都可以自动识别 NONE:所有字段都不可以自动 ...

  6. Jackson常用注解及用法

    最近写项目,用到Jackson的一些注解,总结一下,帮助自己记忆. 1.@JsonIgnore 和 @JsonIgnoreProperties 两个注解可以对照比较后选择使用: @JsonIgnore ...

  7. json序列化反序列化Jackson相关注解

    1.@Transient @Transient表示该属性并非一个到数据库表的字段的映射,ORM框架将忽略该属性:如果一个属性并非数据库表的字段映射,就务必将其标示为@Transient,否则ORM框架 ...

  8. jackson JsonPropertyOrder和@JsonIgnoreProperties注解

    有些时候,我们在和外部系统交互的时候使用了json作为标准的数据交换格式,同时为了安全性考虑,增加了对报文的校验,因此我们需要确保序列化的时候参数有序且不多不少刚好,因为对外的API不像后台和前端交互 ...

  9. jackSon注解– @JsonInclude 注解不返回null值字段

    @Data @JsonInclude(JsonInclude.Include.NON_NULL) public class OrderDTO { private String orderId; @Js ...

  10. Jackson中@JsonProperty等常用注解

    Java生态圈中有很多处理JSON和XML格式化的类库,Jackson是其中比较著名的一个.虽然JDK自带了XML处理类库,但是相对来说比较低级 本文将介绍的Jackson常用注解:精简概述 Jack ...

随机推荐

  1. SpringBoot启动器详解pom.xml

    Spring Boot应用启动器基本的一共有44种,具体如下: 1)spring-boot-starter 这是Spring Boot的核心启动器,包含了自动配置.日志和YAML. 2)spring- ...

  2. Aerospike系列:5:安装AMC

    1:需要安装的包,如果缺少,请安装. python (2.6+) gcc python-devel 安装相应的模块 sudo pip install markupsafe sudo pip insta ...

  3. ES6学习笔记九:修饰器

    一:修饰器(Decorator)是一个函数,用来修改类的行为. 1)定义与使用 function 修饰器名(target) { //target是被修饰对象,可用target.xxx进行调用修改 } ...

  4. join联表查询方法

    $model = Shipping::join('shipping_area', 'shipping_area.shipping_id', '=', 'shipping.shipping_id') - ...

  5. V-rep学习笔记:视觉传感器2

    视觉传感器的属性设置栏中还有如下几个选项: Ignore RGB info (faster): if selected, the RGB information of the sensor (i.e. ...

  6. python之函数用法get()

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法get() #http://www.runoob.com/python/att-dic ...

  7. centos7 在docker swarm中运行Jenkins,利用gitlab的webhook触发自动部署脚本

    1.宿主机中创建目录 mkdir -p /jenkins_home 2.编辑compose文件,文件名jenkins.yml version: '3.4' services: jenkins-upgr ...

  8. Newifi2(D1) 刷入pb-boot和breed的记录

    今天要给一个newifi d1刷系统时发现居然还是原厂的uboot, 使用uboot刷入rom时会进行校验拦截第三方的rom. 之前有刷过这个设备的, 但是已经完全记不清怎么处理的了. 查了一下, 这 ...

  9. masonry瀑布流的使用

    今天在使用masonry.pkgd.min.js瀑布流的时候遇到一个很奇怪的问题,官网显示正常,而我的就是显示不正确,然后我又查看一遍,原来要加这段代码就ok了,记录一下,怕以后还会遇到这个问题 *, ...

  10. 阿里云ECS 利用快照创建磁盘实现无损扩容数据盘

    在扩容数据盘时,若遇到磁盘原因导致无法无损的扩容时,可以临时购买一块独立云磁盘来存放数据,然后将数据盘彻底格式化来解决,以下是操作步骤: 1.  首先基于当前数据盘创建一个快照,备份数据,同时可以利用 ...