##使用gson解析json文件
**json的格式有兩種:**
**1. {}類型,及數據用{}包含;**
**2. []類型,即數據用[]包含;**
下面用個例子,簡單的介紹gson如何解析json,僅使用~
先發兩個json 內容
1、最外層是{}
{
"resp": "ok",
"result": {
"date": "2013-4-19 16:55:58",
"focus": [
{
"summary": "簡介",
"title": "標題",
"url": "http://www.ceshi.com"
},
{
"summary": "簡介22",
"title": "標題22",
"url": "http://www.ceshi22.com"
}
],
"items": [
{
"id": "11",
"name": "名稱",
"price": "88.88"
},
{
"id": "22",
"name": "名稱22",
"price": "100"
}
]
}
}
2、外層是[]
[
{
"addr": "北京",
"age": "22",
"name": "zeng"
},
{
"addr": "上海",
"age": "20",
"name": "zhang"
},
{
"addr": "深圳",
"age": "25",
"name": "wang"
}
]
###**一、使用Gson,解析,關鍵的就是定義好JavaBean類對象**
1、***定義{}類型的JavaBean類***
Bean.java
public class Bean { //若實現Serializable接口,則不用寫下面的SerializedName("字段名"),但成員變量名稱必須與json中一樣
// @SerializedName("resp")
// private String respone;//假如變量命名與解析數據不同,則加上@SerializedName("")
private String resp;
private Result result;
//....下面省略 set ,get
//resultBean類
Result.java
public class Result {
private String date;
private List<FocusItem> focus;
private List<Item> items;
}
FocusItem.java
public class FocusItem {
private String title;
private String summary;
private String url;
}
Item.java
public class Item {
private String name;
private int id;
private float price;
}
2、***定義{}類型的JavaBean類***
Info.java
public class Info {
private String name;
private int age;
private String addr;
}
###**二、解析代碼,一個最外層是{} 一個是[]**
private void parse() {
Gson gson = new Gson();
switch (type) {
//最外層是{},封裝為一個對象
case OBJ:
Bean fromJson = gson.fromJson(readContent, Bean.class);
System.out.println(fromJson.toString());
break;
//最外層是[],封裝為一個數組對象
case ARR:
Type type = new TypeToken<List<Info>>() {}.getType();
Object fromJson2 = gson.fromJson(readContent, type);
List<Info> list = (List<Info>) fromJson2;
break;
}
}

