Gson介紹
Gson(又稱Google Gson)是Google公司發(fā)布的一個(gè)開放源代碼的Java庫(kù),主要用途為序列化Java對(duì)象為JSON字符串擎椰,或反序列化JSON字符串成Java對(duì)象疗疟。而JSON(JavaScript Object Notation) 是一種輕量級(jí)的數(shù)據(jù)交換格式蛀骇,易于人閱讀和編寫湃鹊,同時(shí)也易于機(jī)器解析和生成本昏,廣泛應(yīng)用于各種數(shù)據(jù)的交互中,尤其是服務(wù)器與客戶端的交互痢缎。
下載地址:Gson
對(duì)象轉(zhuǎn)JSON
單獨(dú)轉(zhuǎn)一個(gè)對(duì)象
Article item;
Gson gson = new Gson();
String result = gson.toJson(item);
輸出結(jié)果:
{"id":1,"uuid":"868621d3-d55d-486e-bd7e-1f2df5ec4746","title":"Update Test Title","categories":"Update Test Categories","tags":"Update Test Tags","createTime":"May 23, 2017 11:38:38 PM","updateTime":"May 24, 2017 9:46:46 PM","enable":true}
轉(zhuǎn)一組對(duì)象
List<Article> items;
Gson gson = new Gson();
String result = gson.toJson(items);
輸出結(jié)果:
{"[{"id":1,"uuid":"868621d3-d55d-486e-bd7e-1f2df5ec4746","title":"Update Test Title","categories":"Update Test Categories","tags":"Update Test Tags","createTime":"May 23, 2017 11:38:38 PM","updateTime":"May 24, 2017 9:46:46 PM","enable":true},{"id":2,"uuid":"e58d3d06-8a40-4d64-9329-7a4be87ba1dc","title":"Test Title","categories":"Test Categories","tags":"Test Tags","createTime":"May 23, 2017 11:44:41 AM","updateTime":"May 23, 2017 11:44:41 AM","enable":true},{"id":3,"uuid":"bb662958-398d-4d53-b7c6-9738832b0781","title":"Test Title","categories":"Test Categories","tags":"Test Tags","createTime":"May 23, 2017 8:42:01 PM","updateTime":"May 23, 2017 8:42:01 PM","enable":true}]
設(shè)置日期時(shí)間格式
List<Article> items;
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("yyyy-MM-dd HH:mm:ss");
Gson gson = gsonBuilder.create();
String result = gson.toJson(items);
輸出結(jié)果:
[{"id":1,"uuid":"868621d3-d55d-486e-bd7e-1f2df5ec4746","title":"Update Test Title","categories":"Update Test Categories","tags":"Update Test Tags","createTime":"2017-05-23 23-38-38","updateTime":"2017-05-24 21-46-46","enable":true},{"id":2,"uuid":"e58d3d06-8a40-4d64-9329-7a4be87ba1dc","title":"Test Title","categories":"Test Categories","tags":"Test Tags","createTime":"2017-05-23 11-44-41","updateTime":"2017-05-23 11-44-41","enable":true},{"id":3,"uuid":"bb662958-398d-4d53-b7c6-9738832b0781","title":"Test Title","categories":"Test Categories","tags":"Test Tags","createTime":"2017-05-23 20-42-01","updateTime":"2017-05-23 20-42-01","enable":true}]
隱藏某些域
List<Article> items;
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setExclusionStrategies(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes fieldAttributes) {
String[] skipFields = {"enable"};
String field = fieldAttributes.getName().toLowerCase();
for (String skipField : skipFields)
if (field.equals(skipField))
return true;
return false;
}
@Override
public boolean shouldSkipClass(Class<?> aClass) {
return false;
}
});
Gson gson = gsonBuilder.create();
String result = gson.toJson(items);
輸出結(jié)果:
[{"id":1,"uuid":"868621d3-d55d-486e-bd7e-1f2df5ec4746","title":"Update Test Title","categories":"Update Test Categories","tags":"Update Test Tags","createTime":"2017-05-23 23:38:38","updateTime":"2017-05-24 21:46:46"},{"id":2,"uuid":"e58d3d06-8a40-4d64-9329-7a4be87ba1dc","title":"Test Title","categories":"Test Categories","tags":"Test Tags","createTime":"2017-05-23 11:44:41","updateTime":"2017-05-23 11:44:41"},{"id":3,"uuid":"bb662958-398d-4d53-b7c6-9738832b0781","title":"Test Title","categories":"Test Categories","tags":"Test Tags","createTime":"2017-05-23 20:42:01","updateTime":"2017-05-23 20:42:01"}]
JSON轉(zhuǎn)對(duì)象
首先建立JSON對(duì)應(yīng)的對(duì)象
class JsonHolder {
public boolean success;
public String uuid;
public String message;
}
轉(zhuǎn)單個(gè)對(duì)象
編寫測(cè)試代碼
@Test
public void testJsonObeject() {
String uuid = "4b10e722-0699-4590-90d3-0e7e12358518";
String json = "{\"success\":true, \"uuid\":\"" + uuid + "\"}";
json = "{\"success\":false, \"message\":\"can't create new file!\"}";
JsonHolder item = new Gson().fromJson(json, JsonHolder.class);
System.out.println(item.success);
System.out.println(item.uuid);
System.out.println(item.message);
}
輸出結(jié)果
false
null
can't create new file!
轉(zhuǎn)一組對(duì)象
編寫測(cè)試代碼
@Test
public void testJsonObeject() {
String uuid = "4b10e722-0699-4590-90d3-0e7e12358518";
String json = "{\"success\":true, \"uuid\":\"" + uuid + "\"}";
String longJson = "[" + json + "," + json + "," + json + "]";
JsonHolder[] items = new Gson().fromJson(longJson, JsonHolder[].class);
for (JsonHolder item : items) {
System.out.println(item.success);
System.out.println(item.uuid);
System.out.println(item.message);
}
}
轉(zhuǎn)復(fù)雜對(duì)象
先給出一個(gè)比較復(fù)雜的JSON
{
"error": 0,
"status": "success",
"date": "2014-05-10",
"results": [
{
"currentCity": "南京",
"weather_data": [
{
"date": "周六(今天, 實(shí)時(shí):19℃)",
"dayPictureUrl": "http://api.map.baidu.com/images/weather/day/dayu.png",
"nightPictureUrl": "http://api.map.baidu.com/images/weather/night/dayu.png",
"weather": "大雨",
"wind": "東南風(fēng)5-6級(jí)",
"temperature": "18℃"
},
{
"date": "周日",
"dayPictureUrl": "http://api.map.baidu.com/images/weather/day/zhenyu.png",
"nightPictureUrl": "http://api.map.baidu.com/images/weather/night/duoyun.png",
"weather": "陣雨轉(zhuǎn)多云",
"wind": "西北風(fēng)4-5級(jí)",
"temperature": "21 ~ 14℃"
}
]
}
]
}
構(gòu)造接收這個(gè)JSON的對(duì)象:
class JsonHolder {
public int error;
public String status;
public String date;
public A[] results;
class A {
public String currentCity;
public B[] weather_data;
class B {
public String date;
public String dayPictureUrl;
public String nightPictureUrl;
public String weather;
public String wind;
public String temperature;
}
}
}
編寫測(cè)試代碼
@Test
public void testJsonObeject() throws IOException {
String json = "";
BufferedReader br = new BufferedReader(new FileReader("/home/alan/Documents/WorkSpace/Intellij_IDEA_workspace/MyBlog/test/json.txt"));
String line = "";
while ((line = br.readLine()) != null) {
json += line;
}
br.close();
JsonHolder jsonHolder = new Gson().fromJson(json, JsonHolder.class);
System.out.println(jsonHolder.status);
System.out.println(jsonHolder.results[0].currentCity);
System.out.println(jsonHolder.results[0].weather_data[1].weather);
System.out.println(jsonHolder.results[0].weather_data[1].temperature);
}
輸出結(jié)果:
success
南京
陣雨轉(zhuǎn)多云
21 ~ 14℃