Android JSON解析

和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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值