Java下常見的Json類庫有Gson、JSON-lib和Jackson等,Jackson相對來說比較高效,在項目中主要使用Jackson進行JSON和Java對象轉換,下面給出一些Jackson的JSON操作方法。
一、准備工作
首先去官網下載Jackson工具包,下載地址http://wiki.fasterxml.com/JacksonDownload。Jackson有1.x系列和2.x系列,截止目前2.x系列的最新版本是2.9.0,2.x系列有3個jar包需要下載:
jackson-core-2.2.3.jar(核心jar包,下載地址)
jackson-annotations-2.2.3.jar(該包提供Json注解支持,下載地址)
jackson-databind-2.2.3.jar(下載地址)
可以使用Maven快速依賴引入:
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.0</version> </dependency>
准備序列化的類:
//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; } }
二、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); } }
三、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); } }
四、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"} } }
其它:
@JsonIgnoreProperties此注解是類注解,作用是json序列化時將java bean中的一些屬性忽略掉,序列化和反序列化都受影響。
@JsonIgnore此注解用於屬性或者方法上(最好是屬性上),作用和上面的@JsonIgnoreProperties一樣。
@JsonFormat此注解用於屬性或者方法上(最好是屬性上),可以方便的把Date類型直接轉化為我們想要的模式,比如@JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss")
@JsonSerialize此注解用於屬性或者getter方法上,用於在序列化時嵌入我們自定義的代碼,比如序列化一個double時在其后面限制兩位小數點。
@JsonDeserialize此注解用於屬性或者setter方法上,用於在反序列化時可以嵌入我們自定義的代碼,類似於上面的@JsonSerialize
五、拋磚引玉
除了String之外,還可以操作byte[]等。大致的方法名和操作String的一致。
參考:
http://blog.csdn.net/accountwcx/article/details/24585987(以上內容轉自此篇文章)
http://blog.csdn.net/sbin456/article/details/53305038