一个json对象
{“name”:”sam”,”age”:18,”weight”:60}
/**JSON/
JSONObject jsonObj = new JSONObject(json1);
String name = jsonObj.optString("name");
int age = jsonObj.optInt("age");
int weight = jsonObj.optInt("weight");
/**GSON/
首先我们需要一个实体类
public class People{
public String name;
public int mAge;
public int weight;
}
然后就可以解析了
Gson gson = new Gson();
Poeple people = gson.fromJson(json1, People.class);
一个数字数组
[12,13,15]
/**JSON/
JSONArray jsonArray = new JSONArray(json2);
for(int= 0; i < jsonArray.length();i++) {
int age = jsonArray.optInt(i);
}
/**GSON/
//解析成int数组
Gson gson = new Gson();
int[] ages = gson.fromJson(json2, int[].class);
//解析成Integer的List。
Gson gson = newGson();
List<Integer> ages = gson.fromJson(json2, new
TypeToken<List<Integer>>(){}.getType);
json array中有object
[{“name”:”sam”,”age”:18},{“name”:”leo”,”age”:19},{“name”:”sky”, “age”:20}]
/**JSON/
JSONArray jsonArray = new JSONArray(json3);
for(int= 0; i < jsonArray.length();i++) {
JSONObject jsonObject = sonArray.optJSONObject(i);
String name = jsonObject.optString("name");
int age = jsonObject.optInt("age");
}
/**GSON/
//解析成List。
Gson gson = new Gson();
List<People> peoples = gson.fromJson(json3, new
TypeToke<List<People>>(){}.getType);