【问题标题】:Parse Json in Java not working [closed]Java中的解析Json不起作用[关闭]
【发布时间】:2013-10-23 18:45:52
【问题描述】:

我有以下 json:

{
    "count" : "1567",
    "program" : ["NDBC Meteorological\/Ocean", "International Partners"],
    "owner" : ["NDBC", "Alaska Ocean Observing System"],
    "station" : [{
            "id" : "00922",
            "lat" : "30",
            "lon" : "-90",
            "name" : "OTN201 - 4800922"
        }
    ]
}

我只需要获取station 信息,例如id、lat、lon、name 等。但我无法让它工作,这是我的代码:

//////response_str is the json string///////

  JSONArray  pages =  new JSONArray(response_str);
            for (int i = 0; i < pages.length(); ++i) {
                JSONObject rec = pages.getJSONObject(i);
                JSONObject jsonPage =rec.getJSONObject("station");
                String name= jsonPage.getString("name");
                System.out.println(name);
            }

任何帮助将不胜感激,问候

【问题讨论】:

  • 怎么不工作了?有什么错误吗?例外什么?
  • 在日志猫上打印整个 response_str 的异常
  • jsonPage.getString("name"); 可能会失败,因为station 是一个对象数组,即使它的长度为 1,而不是单个对象...

标签: java android json parsing arrays


【解决方案1】:

station 是 JSONArray 而不是 JSONObject,因此您需要先从主 JSONObject 中获取 JSONArray,然后从 JSONObject 中提取所有 id,lat,lon,..。将您的代码更改为:

JSONArray  pages =  new JSONArray(response_str);
  for (int i = 0; i < pages.length(); ++i) {
      JSONObject rec = pages.getJSONObject(i);
      JSONArray jsonPage =rec.getJSONArray("station");
      // get JSONObject
      JSONObject jsonstation =jsonPage.getJSONObject(0);
      String name= jsonstation.getString("name");
      System.out.println(name);
   }

【讨论】:

  • 感谢我使用此代码的一部分使其工作...感谢它
【解决方案2】:

根是 JSONObject 而不是 JSONArray,它包含三个名为 programm、station 和 owner 的 JSONArray 以及 count 字段。您应该使用 JSON 结构相应地更改您的代码

【讨论】:

  • 谢谢,这让我知道了我在寻找什么。
【解决方案3】:

你根本不需要外部循环

JSONObject jMain = new JSONObject( response_str);
JSONArray jStationList =jMain.getJSONArray("station");
JSONObject jStation =jStationList.getJSONObject(0);

String name= jsonstation.getString("name");

..等

【讨论】:

    【解决方案4】:

    您的问题是当源字符串是 JSONObject 时,您将源字符串称为 JSONArray(外面的括号表示这是一个数组)。下面获取站名。

    JSONObject  pages =  new JSONObject(response_str);
    
    for (int i = 0; i < pages.length(); ++i) 
    {
       JSONArray stationInfo =rec.getJSONArray("station");
       String name= stationInfo.getString("name");
       System.out.println(name);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-09
      • 2014-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多