和XML解析一样JSON解析的方式也有很多,还有更方便的第三方库工具。
使用AndroidSDK中的org.json包
解析数据例子:
//解析数据推荐用这些方法,这些方法在解析时,如果对应字段不存在会返回空值或者0,不会报错。
JSONObject jsonObj = new JSONObject(jsonString);
String name = jsonObj.optString("name");
int age = jsonObj.optInt("age");
int weight = jsonObj.optInt("weight");
//Object opt(String name)
//boolean optBoolean(String name)
//double optDouble(String name)
//JSONArray optJSONArray(String name)
//JSONObject optJSONObject(String name)
//解析包含对象复杂数组JSON:
JSONArray jsonArray = new JSONArray(jsonString);
for (int = 0; i < jsonArray.length();i++) {
JSONObject jsonObject = jsonArray.optJSONObject(i);
String name = jsonObject.optString("name");
int age = jsonObject.optInt("age");
}
详解http://blog.csdn.net/onlyonecoder/article/details/8490924
http://developer.android.com/intl/zh-cn/reference/org/json/package-summary.html
使用JsonReader和JsonWriter
在android3.0又为在android.util包JsonReader和JsonWriter来进行json的解析和生成。
http://developer.android.com/intl/zh-cn/reference/android/util/JsonReader.html
http://developer.android.com/intl/zh-cn/reference/android/util/JsonWriter.html
//JsonReader的使用方式和XML的PULL解析器类似。
JsonReader reader = new JsonReader(new InputStreamReader(inStream, "UTF-8"));
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("name")) {
username = reader.nextString();
} else if (name.equals("followers_count")) {
followersCount = reader.nextInt();
} else {
reader.skipValue();
}
}
reader.endObject();
JsonWriter writer = new JsonWriter(new OutputStreamWriter(os, "UTF-8"));
writer.beginObject();
writer.name("name").value(user.getName());
writer.name("followers_count").value(user.getFollowersCount());
writer.endObject();
使用GSON等第三方库实现
GSON是谷歌出的,
还有一些其他的第三方的比如淘宝的FastJSON等,和Gson类似,传JSON数据的String和要转换的实体类对象,然后直接解析得到对象。
Gson gson1 = new Gson();
Poeple people = gson1.fromJson(jsonString1, People.class);
Gson gson2 = new Gson();
int[] ages = gson2.fromJson(jsonString2, int[].class);
Gson gson3 = new Gson();
List<People> peoples = gson3.fromJson(jsonString, new TypeToke<List<People>>(){}.getType);