1.jsonObject 简单对象解析
String json = "{\n" +
"\t\"id\":2, \"name\":\"金鱼\", \n" +
"\t\"price\":12.3, \n"+
"\t\"imagePath\":\"http://blog.csdn.net/qq_29269233/L05_Server/images/f1.jpg\"\n" +
"}\n"
JSONObject jsonObject=new JSONObject(json);
String id=jsonObject.optString("id");
Log.d("json","json id="+id);
String name=jsonObject.optString("name");
Log.d("json","json name="+name);
double price=jsonObject.optDouble("price");
Log.d("json","json price="+price);String imagePath=jsonObject.optString("imagePath");
Log.d("json","json imagePath="+imagePath);}

2. JSONArray 简单数组
String jsonarray = "[\n" +
" {\n" + " \"id\": 1,
\n" + " \"imagePath\": \"http://blog.csdn.net/qq_29269233/f1.jpg\",
\n" + " \"name\": \"金鱼1\",
\n" + " \"price\": 12.3\n" + " },
\n" + " {
\n" + " \"id\": 2,
\n" + " \"imagePath\": \"http://blog.csdn.net/qq_29269233/f2.jpg\",
\n" + " \"name\": \"金鱼2\",\n" + " \"price\": 12.5\n" + "
}
\n" + "]";
JSONArray jsonArray=new JSONArray(jsonarray);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String id=jsonObject1.optString("id");
Log.d("json","json id="+id);
String imagePath=jsonObject1.optString("imagePath");
Log.d("json","json imagePath="+imagePath);
String name=jsonObject1.optString("name");
Log.d("json","json name="+name);
double price=jsonObject1.optDouble("price");
Log.d("json","json price="+price);
}

JsonObject + JSONArray 组合

JSONObject object=new JSONObject(jsonlist);
String resultcode= object.optString("resultcode");
Log.d("json","json reason="+resultcode);
String reason= object.optString("reason");
Log.d("json","json reason="+reason);
JSONArray array=object.getJSONArray("result");
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject1=array.getJSONObject(i);
String city= jsonObject1.optString("city");
Log.d("json","json city="+city);
String PM= jsonObject1.optString("PM2.5");
Log.d("json","json PM="+PM);
String AQI=jsonObject1.optString("AQI");
Log.d("json","json AQI="+AQI);
String quality= jsonObject1.optString("quality");
Log.d("json","json quality="+quality);
String PM10= jsonObject1.optString("PM10");
Log.d("json","json PM10="+PM10);
String CO= jsonObject1.optString("CO");
Log.d("json","json CO="+CO);
String NO2= jsonObject1.optString("NO2");
Log.d("json","json NO2="+NO2);
String O3= jsonObject1.optString("O3");
Log.d("json","json O3="+O3);
String SO2= jsonObject1.optString("SO2");
Log.d("json","json SO2="+SO2);
String time= jsonObject1.optString("time");
Log.d("json","json time="+time);
}
String error_code= object.optString("error_code");
Log.d("json","json error_code="+error_code);

网友评论