一般解析json方法自己写起来较为繁琐,利用开源的API可以节省很多事,达到快速的开发。


1) 自己写的代码:

例如:

private void parserJSON(String strJSON)

{

try

{

JSONArray jsonArray = new JSONArray(strJSON);

for (int j = 0; j < jsonArray.length(); j++)

{

JSONObject jsonObject = jsonArray.getJSONObject(j);

String icon1Url = jsonObject.getString("icon1Url");

String fristTile = jsonObject.getString("fristTitle");

String title = jsonObject.getString("title");

String message = jsonObject.getString("message");

String p_w_picpathUrl = jsonObject.getString("p_w_picpathUrl");

String time = jsonObject.getString("time");

String from = jsonObject.getString("from");

mList.add(new HomeData(icon1Url, fristTile, title, message, p_w_picpathUrl, time, from));

}


}

catch (JSONException e)

{

e.printStackTrace();

}


}


如果json的数据多起来,就要写很多的get,就比较烦了


2) 用gson解析:

例如:


private void parserJSON(String strJSON)

{

Gson gson = new Gson();

Type type = new TypeToken<List<HomeData>>()

{

}.getType();

List<HomeData> mDataInfo = gson.fromJson(strJSON, type);

}

总结: 两者用起来存数据的类HomeData,容器List这多少不了,用了Gson就是不用自己写get语句

不用写try catch,方便了很多。


Gson用法:

1. 首先,从 code.google.com/p/google-gson/downloads/list下载GsonAPI:

google-gson-2.2.4-release.zip

2. 把gson-2.2.4.jar copy到libs(项目res目录新建一个libs文件夹)中。

3. 代码中使用:就是上面的 2) 的写法,这是解析一个jsonArray,类的属性要跟json文件中的 key,完全一致,属性的类型是value的类型