Json数据解析(二)

来源:互联网 发布:文华期货软件 编辑:程序博客网 时间:2024/05/16 15:02
这个格式使用如下代码解析
 
try {
    JSONObject jsonObject = new JSONObject(json);
    JSONObject weatherinfo = jsonObject.getJSONObject("weatherinfo");
 
    System.out.println(weatherinfo.getString("city"));
    System.out.println(weatherinfo.getString("cityid"));
    System.out.println(weatherinfo.getString("temp"));
    System.out.println(weatherinfo.getString("WD"));
 
catch (JSONException e) {
    e.printStackTrace();
}
  其中第一行代码 JSONObject jsonObject = new JSONObject(json);//json 即为你的字符串
     
 比如现在天气信息是多个城市的,并非只有北京市。
{"weatherinfo":[{"city":"北京","cityid":"101010100","temp":"4","WD":"东风","WS":"2级","SD":"75%","WSE":"2","time":"10:45","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB","njd":"暂无实况","qy":"1011"},{"city":"天津","cityid":"101010100","temp":"4","WD":"东风","WS":"2级","SD":"75%","WSE":"2","time":"10:45","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB","njd":"暂无实况","qy":"1011"}]}
以下代码适用。   
 
try {
    JSONObject jsonObject=new JSONObject(json);
    JSONArray jsonArray=jsonObject.getJSONArray("weatherinfo");
  for (int i=0;i<jsonArray.length();i++){
      JSONObject object = jsonArray.getJSONObject(i);
      System.out.println(object.getString("city"));
      System.out.println(object.getString("cityid"));
      System.out.println(object.getString("temp"));
      System.out.println(object.getString("WD"));
  }
catch (JSONException e) {
    e.printStackTrace();
}
1 0