如何在Android项目中解析 json数据

今天就跟大家聊聊有关如何在Android项目中解析 json数据,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

 Android json数据解析详解

移动开发经常要与服务器数据交互,也常使用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数据,其实都是一样的。多解析一次而已。

看完上述内容,你们对如何在Android项目中解析 json数据有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。