##使用gson解析json文件
**json的格式有两种:**
**1. {}类型,及数据用{}包含;**
**2. []类型,即数据用[]包含;**
下面用个例子,简单的介绍gson如何解析json,仅使用~
先发两个json 内容
1、最外层是{}
{
"resp": "ok",
"result": {
"date": "-4-19 16:55:58",
"focus": [
{
"summary": "简介",
"title": "标题",
"url": ""
},
{
"summary": "简介22",
"title": "标题22",
"url": ""
}
],
"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;
}
}