Jackson(使用注解)
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(使用注解)的更多相关文章
- jackson annotations注解详解
jackson中常用到的注解 猛击下面的连接地址 http://blog.csdn.net/sdyy321/article/details/40298081
- jackson annotations注解详解 (zhuan)
http://blog.csdn.net/sdyy321/article/details/40298081 ************************************** 官方WIKI: ...
- jackson基于注解的简单使用
Jackson提供了一系列注解,方便对JSON序列化和反序列化进行控制,下面介绍一些常用的注解. 1.@JsonIgnore 此注解用于属性上,作用是进行JSON操作时忽略该属性. 2.@JsonFo ...
- jackson 常用注解,比如忽略某些属性,驼峰和下划线互转
一般情况下使用JSON只使用了java对象与字符串的转换,但是,开发APP时候,我们经常使用实体类来做转换:这样,就需要用到注解: Jackson默认是针对get方法来生成JSON字符串的,可以使用注 ...
- Jackson /常用注解/ annotation(转)
1.@JsonAutoDetect 自动检测,(作用在类上)来开启/禁止自动检测. fieldVisibility:字段的可见级别 ANY:任何级别的字段都可以自动识别 NONE:所有字段都不可以自动 ...
- Jackson常用注解及用法
最近写项目,用到Jackson的一些注解,总结一下,帮助自己记忆. 1.@JsonIgnore 和 @JsonIgnoreProperties 两个注解可以对照比较后选择使用: @JsonIgnore ...
- json序列化反序列化Jackson相关注解
1.@Transient @Transient表示该属性并非一个到数据库表的字段的映射,ORM框架将忽略该属性:如果一个属性并非数据库表的字段映射,就务必将其标示为@Transient,否则ORM框架 ...
- jackson JsonPropertyOrder和@JsonIgnoreProperties注解
有些时候,我们在和外部系统交互的时候使用了json作为标准的数据交换格式,同时为了安全性考虑,增加了对报文的校验,因此我们需要确保序列化的时候参数有序且不多不少刚好,因为对外的API不像后台和前端交互 ...
- jackSon注解– @JsonInclude 注解不返回null值字段
@Data @JsonInclude(JsonInclude.Include.NON_NULL) public class OrderDTO { private String orderId; @Js ...
- Jackson中@JsonProperty等常用注解
Java生态圈中有很多处理JSON和XML格式化的类库,Jackson是其中比较著名的一个.虽然JDK自带了XML处理类库,但是相对来说比较低级 本文将介绍的Jackson常用注解:精简概述 Jack ...
随机推荐
- gdb 小技巧
https://www.gitbook.com/book/wizardforcel/100-gdb-tips/details
- zip 文件下载函数封装
代码: export default { /** * 下载文件 */ exportFile: (fileUrl) => { if (fileUrl) { let exportFrame = do ...
- Axure 图片轮播(广告通栏图片自动播放效果)
baiduYunpan:http://pan.baidu.com/s/1eRPCy90 里面的“图片轮播”部件即可实现这个功能
- OpenWrt/LEDE配置OpenVPN Server
安装openvpn不再赘述 准备证书文件主要有以下文件: (服务端)ca.crtdh2048.pemserver.crtserver.key(客户端)ca.crtclient01.keydp-clie ...
- ArcGIS10.1正式版全套下载、安装与破解(附ArcGIS10.1全套下载地址)【转】
一.准备文件1.ArcGIS10.1安装包:ArcGIS_Desktop_10.1_129026(en)2.认证服务:Pre-release_license_manager3.注册机:arcgis10 ...
- 存储过程—导出table数据为inser sqlt语句
Sql Server Management Studio没有将table中数据导出为insert语句的功能. 下面一个很有用的存储过程,可以把某张表的数据导出为insert sql语句.当然Oracl ...
- asiHttpRequst 学习地址
最全面的地址 http://blog.csdn.net/uxyheaven/article/details/7884734 http://allseeing-i.com/ASIHTTPRequest/ ...
- dx11的一些数据结构
功能是什么创建一个设备(device)来代表显示适配器(display adapter)并且创建一个交换链(swap chain)用于渲染 设备device在dx11里是用来干什么的从ID3DX11D ...
- WebDriver基本操作入门及UI自动化练手页面
在这里集中了我们在做UI自动化时常见的一些控件操作.希望能对新手有帮助. 下载地址:http://files.cnblogs.com/zhangfei/demo.rar package com.tes ...
- 进阶之路(基础篇) - 008 SPI数据传输(库函数方法)
主机端: /********************************* 代码功能:SPI数据传输(主机端) 引脚说明: SS/CS:片选(高电平屏蔽,低电平启用) MOSI :主机送出信号 M ...