您的位置:首页 > Web前端 > JavaScript

Gson解析复杂JSON对象

2015-01-08 10:58 344 查看
例如以下格式JSON:



建立对应的Java对象,注意内部类要定义成静态的

public class HResult {

public String total;
public String records;
public String page;

public List<HCell> rows;

static class HCell{
public List<String> cell;
public String id;
}

}


使用Gson进行解析

public static void main(String[] args) {
String json = "{\"total\":\"1\",\"rows\":[{\"cell\":[\"c1\",\"c2\",\"没有检索到相关历史信息,请点击[我要留言]\",\"c4\",\"c5\",\"c6\",\"c7\"],\"id\":\"999999999999999999999999999999\"}],\"records\":\"0\",\"page\":\"1\"}";

Gson gson = new Gson();

HResult hResult = gson.fromJson(json, new TypeToken<HResult>(){}.getType());

System.out.println("total:"+hResult.total);
System.out.println("records:"+hResult.records);
System.out.println("page:"+hResult.page);

List<HResult.HCell> list = hResult.rows;
for(HResult.HCell row:list){
System.out.println("cell:"+row.cell);
System.out.println("id:"+row.id);
}
}


运行结果:

run:
total:1
records:0
page:1
cell:[c1, c2, 没有检索到相关历史信息,请点击[我要留言], c4, c5, c6, c7]
id:999999999999999999999999999999
成功构建 (总时间: 0 秒)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: