源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Android json数据解析详解及实例代码

  • 时间:2021-10-13 02:27 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Android json数据解析详解及实例代码
[b] Android json数据解析详解[/b] 移动开发经常要与服务器数据交互,也常使用json数据格式,那就说说Android json解析。 1.最简单json格式解析如下:
         //解析json 
ry {   
JSONTokener jsonParser = new JSONTokener(strResult);  
JSONObject jsonObj = (JSONObject) jsonParser.nextValue();  
String strsportsTitle = jsonObj.getString("sportsTitle");  
  int nid= jsonObj.getInt("id");                 
 } catch (JSONException e) {   
   System.out.println("Json parse error");   
   e.printStackTrace();   
}  
字符串strResult就是需要解析json数据了。用过json数据格式都知道,json数据格式是一个键对应一个值。你可以先打印出原始数据strResult,就知道jsonObj.getString("sportsTitle");这双引号里面键是什么。  2.数组形式json数据解析如下:
try { 
    JSONArray jsonArray = new JSONArray(strResult); 
    for (int i = 0; i < jsonArray.length(); i++) { 
      JSONObject jsonObj = jsonArray.optJSONObject(i); 
      id[i] = jsonObj.getInt("id"); 
      time[i] = jsonObj.getString("time"); 
      users[i] = jsonObj.getString("users"); 
      roomTitle[i] = jsonObj.getString("roomTitle"); 
    } 
  } catch (JSONException e) { 
    System.out.println("Jsons parse error !"); 
    e.printStackTrace(); 
  } 
3.json里面嵌套json数据解析如下:
              try { 
  JSONArray jsonArray = new JSONArray(strResult); 
  for (int i = 0; i < jsonArray.length(); i++) { 
    JSONObject jsonObj = jsonArray.optJSONObject(i); 
    String strachievement = jsonObj.getString("achievement"); 
      String strmember = jsonObj.getString("member"); 
 
    try { 
      JSONTokener jsonParser1 = new JSONTokener( 
          achievement); 
      JSONObject jsonObj1 = (JSONObject) jsonParser1 
          .nextValue(); 
      nametype[i] = jsonObj1.getString("name"); 
      type[i] = jsonObj1.getString("type"); 
 
    } catch (JSONException e) { 
      System.out.println("Json parse error"); 
      e.printStackTrace(); 
    } 
  } 
} catch (JSONException e) { 
  System.out.println("Json parse error"); 
  e.printStackTrace(); 
}  
嵌套json数据,其实都是一样的。多解析一次而已。 感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部