Java下常見的Json類庫有Gson、JSON-lib和Jackson等,Jackson相對來說比較高效,在項(xiàng)目中主要使用Jackson進(jìn)行JSON和Java對象轉(zhuǎn)換,下面給出一些Jackson的JSON操作方法。
一、準(zhǔn)備工作
Jackson有1.x系列和2.x系列,2.x系列有3個(gè)jar包需要下載:
jackson-core-2.2.3.jar(核心jar包)
jackson-annotations-2.2.3.jar(該包提供Json注解支持)
jackson-databind-2.2.3.jar
maven依賴就夠了
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>

import java.util.Date;
/**
* JSON序列化和反序列化使用的User類
*/
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;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", birthday=" + birthday +
", email='" + email + '\'' +
'}';
}
}
二、JAVA對象轉(zhuǎn)JSON[JSON序列化]
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonDemo {
public static void main(String[] args) throws ParseException, IOException {
User user = new User();
user.setName("zhangsan");
user.setEmail("zhangsan@163.com");
user.setAge(20);
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
user.setBirthday(dateformat.parse("1996-10-01"));
/**
* ObjectMapper是JSON操作的核心,Jackson的所有JSON操作都是在ObjectMapper中實(shí)現(xiàn)。
* ObjectMapper有多個(gè)JSON序列化的方法,可以把JSON字符串保存File、OutputStream等不同的介質(zhì)中。
* writeValue(File arg0, Object arg1)把a(bǔ)rg1轉(zhuǎn)成json序列,并保存到arg0文件中。
* writeValue(OutputStream arg0, Object arg1)把a(bǔ)rg1轉(zhuǎn)成json序列,并保存到arg0輸出流中。
* writeValueAsBytes(Object arg0)把a(bǔ)rg0轉(zhuǎn)成json序列,并把結(jié)果輸出成字節(jié)數(shù)組。
* writeValueAsString(Object arg0)把a(bǔ)rg0轉(zhuǎn)成json序列,并把結(jié)果輸出成字符串。
*/
ObjectMapper mapper = new ObjectMapper();
//User類轉(zhuǎn)JSON
//輸出結(jié)果:{"name":"zhangsan","age":20,"birthday":844099200000,"email":"zhangsan@163.com"}
String json = mapper.writeValueAsString(user);
System.out.println(json);
//Java集合轉(zhuǎn)JSON
//輸出結(jié)果:[{"name":"zhangsan","age":20,"birthday":844099200000,"email":"zhangsan@163.com"}]
List<User> users = new ArrayList<User>();
users.add(user);
String jsonlist = mapper.writeValueAsString(users);
System.out.println(jsonlist);
}
}
三、JSON轉(zhuǎn)Java類[JSON反序列化]
public class JacksonDemo {
public static void main(String[] args) throws ParseException, IOException {
String json = "{\"name\":\"zhangsan\",\"age\":20,\"birthday\":844099200000,\"email\":\"zhangsan@163.com\"}";
/**
* ObjectMapper支持從byte[]、File、InputStream、字符串等數(shù)據(jù)的JSON反序列化。
*/
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(json, User.class);
System.out.println(user);
}
}
User{name='zhangsan', age=20, birthday=Tue Oct 01 00:00:00 CST 1996, email='zhangsan@163.com'}
public class JacksonDemo {
public static ObjectMapper mapper = new ObjectMapper();
public static void main(String[] args) throws ParseException, IOException {
String json = "[{\"name\":\"zhangsan\",\"age\":20,\"birthday\":844099200000,\"email\":\"zhangsan@163.com\"}]";
List<User> beanList = mapper.readValue(json, new TypeReference<List<User>>() {});
System.out.println(beanList);
}
}
[User{name='zhangsan', age=20, birthday=Tue Oct 01 00:00:00 CST 1996, email='zhangsan@163.com'}]
四、JSON注解
Jackson提供了一系列注解,方便對JSON序列化和反序列化進(jìn)行控制,下面介紹一些常用的注解。
@JsonIgnore 此注解用于屬性上,作用是進(jìn)行JSON操作時(shí)忽略該屬性。
@JsonFormat 此注解用于屬性上,作用是把Date類型直接轉(zhuǎn)化為想要的格式,如@JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss")。
@JsonProperty 此注解用于屬性上,作用是把該屬性的名稱序列化為另外一個(gè)名稱,如把trueName屬性序列化為name,@JsonProperty("name")。
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Date;
/**
* JSON序列化和反序列化使用的User類
*/
public class User {
private String name;
//不JSON序列化年齡屬性
@JsonIgnore
private Integer age;
//格式化日期屬性
@JsonFormat(pattern = "yyyy年MM月dd日")
private Date birthday;
//序列化email屬性為mail
@JsonProperty("my_email")
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;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", birthday=" + birthday +
", email='" + email + '\'' +
'}';
}
}
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class JacksonDemo {
public static void main(String[] args) throws ParseException, IOException {
User user = new User();
user.setName("zhangsan");
user.setEmail("zhangsan@163.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":"zhangsan","birthday":"1996年09月30日","my_email":"zhangsan@163.com"}
Jackson常用注解詳解:@JsonProperty
最常見的使用方式之一就是改變某個(gè)成員屬性所使用的JSON名稱,例如:
public class Name {
@JsonProperty("firstName")
public String _first_name;
}
將會生成如下所示的JSON數(shù)據(jù)結(jié)果:
{ "firstName" : "Bob" }
而不是:
{ "_first_name" : "Bob"}
忽略屬性時(shí)使用的注解: @JsonIgnore
有時(shí)POJO包括了一些你不希望輸出的屬性,在這種情況下,你可以進(jìn)行如下操作:
public class Value {
public int value;
@JsonIgnore
public int internalValue;
}
這時(shí)得到的JSON數(shù)據(jù)結(jié)果如下:
{ "value" : 42 }
或者,你可能忽略掉某些從JSON數(shù)據(jù)中得到的屬性,如果是這樣,你可以使用:
@JsonIgnoreProperties({ "extra", "uselessValue" })
public class Value {
public int value;
}
這樣就能夠處理像如下所示的JSON數(shù)據(jù):
{
"value" : 42,
"extra" : "fluffy",
"uselessValue" : -13
}
最后,你甚至能簡單地忽略掉從JSON(由于在應(yīng)用中沒有完全匹配的POJO)中獲得的所有“多余的”屬性。你可以通過添加如下代碼完成這個(gè)操作:
@JsonIgnoreProperties(ignoreUnknown=true)
public class PojoWithAny {
public int value;
}
選擇更多/更少指定類型時(shí)使用的注解
在有些情況下,Jackson在讀入或輸出一個(gè)成員屬性時(shí),所選用的類型可能并不是你想要的:
當(dāng)讀?。ǚ葱蛄谢r(shí),聲明的類型可能是一個(gè)基本類型,但是你確切地知道應(yīng)該使用的實(shí)現(xiàn)類型(ps:也就說,我們需要反序列化后生成的對象是實(shí)現(xiàn)類型的)
當(dāng)輸出(序列化)時(shí),Jackson默認(rèn)使用的是給定的運(yùn)行時(shí)類型;但是你可能不想輸出那個(gè)類型的所有信息,而僅僅是它的父類型所囊括的信息。
在這些應(yīng)用場景,你可以使用如下的注解進(jìn)行處理:
public class ValueContainer {
// 雖然代碼中使用的類型是 Value, 但我們希望讀取到的JSON 之后得到的對象的類型是 ValueImpl
@JsonDeserialize(as=ValueImpl.class)
public Value value;
// 雖然運(yùn)行時(shí)的類型可能是 AdvancedType , 但是我們確實(shí)想序列化
// 成為 BasicType ; 有兩種處理方式:
@JsonSerialize(as=BasicType.class)
// 或者我們可以這樣: @JsonSerialize(typing=Typing.STATIC)
public BasicType another;
}