Android如何解析json数组对象

来源:互联网 发布:网络销售模式有哪些 编辑:程序博客网 时间:2024/06/05 11:43

json是种常用的数据传输格式,在android开发中,如何借助java语言实现对json数组对象的解析呢,请参阅下面的关键代码:

[java] view plain copy
  1. import org.json.JSONArray;  
  2. import org.json.JSONObject;  
  3.   
  4. //jsonData的数据格式:[{ "id": "27JpL~jd99w9nM01c000qc", "version": "abc" },{ "id": "27JpL~j6UGE0LX00s001AH", "version": "bbc" },{ "id": "27JpL~j7YkM0LX01c000gt", "version": "Wa_" }]  
  5. JSONArray arr = new JSONArray(jsonData);  
  6. for (int i = 0; i < arr.length(); i++) {  
  7.     JSONObject temp = (JSONObject) arr.get(i);  
  8.     String id = temp.getString("id");  
  9.     String id = temp.getString("version");  
  10. }  

主要用到的类:JSONArray和JSONObject


android 读取json数据(遍历JSONObject和JSONArray)(转)

  • public String getJson(){  
  •         String jsonString = "{\"FLAG\":\"flag\",\"MESSAGE\":\"SUCCESS\",\"name\":[{\"name\":\"jack\"},{\"name\":\"lucy\"}]}";//json字符串  
  •         try {  
  •             JSONObject result = new JSONObject(jsonstring);//转换为JSONObject  
  •             int num = result.length();  
  •             JSONArray nameList = result.getJSONArray("name");//获取JSONArray  
  •             int length = nameList.length();  
  •             String aa = "";  
  •             for(int i = 0; i < length; i++){//遍历JSONArray  
  •                 Log.d("debugTest",Integer.toString(i));  
  •                 JSONObject oj = nameList.getJSONObject(i);  
  •                 aa = aa + oj.getString("name")+"|";  
  •                   
  •             }  
  •             Iterator<?> it = result.keys();  
  •             String aa2 = "";  
  •             String bb2 = null;  
  •             while(it.hasNext()){//遍历JSONObject  
  •                 bb2 = (String) it.next().toString();  
  •                 aa2 = aa2 + result.getString(bb2);  
  •                   
  •             }  
  •             return aa;  
  •         } catch (JSONException e) {  
  •             throw new RuntimeException(e);  
  •         }  
  •     }  

 

原文: http://zhaojianping.blog.51cto.com/725123/629526


原创粉丝点击