Jackson常用注解介绍

一般情况下使用JSON只使用了java对象与字符串的转换,但是,开发APP时候,我们经常使用实体类来做转换;这样,就需要用到注解;
Jackson默认是针对get方法来生成JSON字符串的,可以使用注解来做一些特殊用途;常见的使用如下:
1 排除属性
@JsonIgnore,一般标记在属性或方法上;作用于序列化与反序列化;
@JsonIgnoreProperties,如果是代理类,由于无法标记在属性或方法上,所以,可以标记在类声明上;也作用于反序列化时的字段解析;
2 属性别名
@JsonProperty,序列化/反序列化都有效;
3 属性排序
@JsonPropertyOrder,注释在类声明中;
4 属性格式转换,使用自定义序列化/反序列化来处理;
@JsonSerialize,序列化;
@JsonDeserialize,反序列化;
注意:在使用hibernate的时候,查询数据库后产生的实体类是个代理类,这时候转换JSON会报错;
解决方法有两种:
1)设置FAIL_ON_EMPTY_BEANS属性,告诉Jackson空对象不要抛异常;
mapper.disable(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS);
2)使用@JsonIgnoreProperties注解
在实体类声明处加上@JsonIgnoreProperties(value = {"hibernateLazyInitializer", "handler"})注解;
建议使用@JsonIgnoreProperties注解,这样生成的JSON中不会产生多余的字段;
5 父/子关联
@JsonManagedReference,放在父亲类中;
@JsonBackReference,放在孩子类中;
6 去掉包装
@JsonUnwrapped,意思如下:
Ability to map JSON like
{
"name" : "home",
"latitude" : 127,
"longitude" : 345
}
to classes defined as:
class Place {
public String name;
@JsonUnwrapped
public Location location;
}
class Location {
public int latitude, longitude;
}


7 JSON序列化和反序列化使用的User类
import java.util.Date;


public class User {
private String name;
private Integer age;
private Date birthday;
private String email;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}

public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}

public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}


8 JAVA对象转JSON[JSON序列化]


import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import com.fasterxml.jackson.databind.ObjectMapper;


public class JacksonDemo {
public static void main(String[] args) throws ParseException, IOException {
User user = new User();
user.setName("小民");
user.setEmail("xiaomin@sina.com");
user.setAge(20);
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
user.setBirthday(dateformat.parse("1996-10-01"));

/**
* ObjectMapper是JSON操作的核心,Jackson的所有JSON操作都是在ObjectMapper中实现。
* ObjectMapper有多个JSON序列化的方法,可以把JSON字符串保存File、OutputStream等不同的介质中。
* writeValue(File arg0, Object arg1)把arg1转成json序列,并保存到arg0文件中。
* writeValue(OutputStream arg0, Object arg1)把arg1转成json序列,并保存到arg0输出流中。
* writeValueAsBytes(Object arg0)把arg0转成json序列,并把结果输出成字节数组。
* writeValueAsString(Object arg0)把arg0转成json序列,并把结果输出成字符串。
*/
ObjectMapper mapper = new ObjectMapper();

//User类转JSON
//输出结果:{"name":"小民","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"}
String json = mapper.writeValueAsString(user);
System.out.println(json);

//Java集合转JSON
//输出结果:[{"name":"小民","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"}]
List<User> users = new ArrayList<User>();
users.add(user);
String jsonlist = mapper.writeValueAsString(users);
System.out.println(jsonlist);
}
}


9 JSON转Java类[JSON反序列化]


import java.io.IOException;
import java.text.ParseException;
import com.fasterxml.jackson.databind.ObjectMapper;


public class JacksonDemo {
public static void main(String[] args) throws ParseException, IOException {
String json = "{\"name\":\"小民\",\"age\":20,\"birthday\":844099200000,\"email\":\"xiaomin@sina.com\"}";

/**
* ObjectMapper支持从byte[]、File、InputStream、字符串等数据的JSON反序列化。
*/
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(json, User.class);
System.out.println(user);
}
}


10 JSON注解


Jackson提供了一系列注解,方便对JSON序列化和反序列化进行控制,下面介绍一些常用的注解。
@JsonIgnore 此注解用于属性上,作用是进行JSON操作时忽略该属性。
@JsonFormat 此注解用于属性上,作用是把Date类型直接转化为想要的格式,如@JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss")。
@JsonProperty 此注解用于属性上,作用是把该属性的名称序列化为另外一个名称,如把trueName属性序列化为name,@JsonProperty("name")。


import java.util.Date;
import com.fasterxml.jackson.annotation.*;


public class User {
private String name;

//不JSON序列化年龄属性
@JsonIgnore 
private Integer age;

//格式化日期属性
@JsonFormat(pattern = "yyyy年MM月dd日")
private Date birthday;

//序列化email属性为mail
@JsonProperty("mail")
private String email;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}

public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}

public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}






import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;


import com.fasterxml.jackson.databind.ObjectMapper;


public class JacksonDemo {
public static void main(String[] args) throws ParseException, IOException {
User user = new User();
user.setName("小民");
user.setEmail("xiaomin@sina.com");
user.setAge(20);
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
user.setBirthday(dateformat.parse("1996-10-01"));

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(user);
System.out.println(json);
//输出结果:{"name":"小民","birthday":"1996年09月30日","mail":"xiaomin@sina.com"}
}
}
参考:
http://wiki.fasterxml.com/JacksonAnnotations
http://www.cowtowncoder.com/blog/archives/2011/10/entry_463.html
http://www.07net01.com/linux/Jacksonzhujiexuexicankao_44238_1356358422.htm


Download
去官网下载Jackson工具包,下载地址http://wiki.fasterxml.com/JacksonDownload。Jackson有1.x系列和2.x系列
jackson-core-2.2.3.jar(核心jar包,下载地址)
jackson-annotations-2.2.3.jar(该包提供Json注解支持,下载地址)
jackson-databind-2.2.3.jar(下载地址)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值