(《第一行代码》)整理总结:
准备工作
[{"id":"1", "version":"1.0", "name":"Ha Ha"}
{"id":"2", "version":"2.0", "name":"He He"}
{"id":"3", "version":"3.0", "name":"Hei Hei"}]
1、使用JSONObject
private void parseJSONWithJSONObject(String jsonData) {
try {
JSONArray jsonArray = new JSONArray(jsonData);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = jsonObject.getString("id");
String name = jsonObject.getString("name");
String version = jsonObject.getString("version");
Log.d("MainActivity", "id is" + id);
Log.d("MainActivity", "name is" + name);
Log.d("MainActivity", "version is" + version);
}
} catch (Exception e) {
e.printStackTrace();
}
}
2、使用GSON
首先新建一个App类
public class App {
private String id, name, version;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
然后新增一个方法:
private void parseJSONWithGSON(String jsonData) {
Gson gson = new Gson();
List<App> appList = gson.fromJson(jsonData, new TypeToken<List<App>>() {}.getType());
for (App app : appList) {
Log.d("MainActivity", "id is" + app.getId());
Log.d("MainActivity", "name is" + app.getName());
Log.d("MainActivity", "version is" + app.getVersion());
}
}
最后调用的时候:
parseJAONWithGSON(response);