迭代/解析此JSON响应

时间:2016-10-17 17:41:14

标签: java android arrays json

我的应用程序中有一些JSON源,它使用有效的语法和密钥的使用正确解析。我使用类似于以下的方法:

try {

    JSONObject jsonObj = new JSONObject(response);
    if(jsonObj.length() > 0){
        Iterator keys = jsonObj.keys();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            JSONObject obj = (JSONObject) jsonObj.get(key);

            String myString = obj.get("fieldname").toString();

            ...
        }
    }
} catch(e) {
    ...
}

但是,我所拥有的一个JSON feed的样式如下所示,需要稍微区别地解析:

{
"10":["111","aaa","bbb","213sdg","1.0","-0.343"],
"20":["111","aaa","bbb","213sdg","1.0","-0.343"],
"30":["111","aaa","bbb","213sdg","1.0","-0.343"],
"40":["111","aaa","bbb","213sdg","1.0","-0.343"],
"50":["111","aaa","bbb","213sdg","1.0","-0.343"]
}

我尝试使用JSONArray代替JSONObject,但是当Feed没有字段名/键时,try {}子句仍然会出现需要字段名/键的错误。

是否有一种简单的方法可以迭代此样式Feed,而无需更改Feed输出?非常感谢

编辑:更改了JSON对象键以显示我实际上使用了不同的数字

2 个答案:

答案 0 :(得分:0)

试试此代码

try{
  JSONObject jObject = new JSONObject(yourStringFromYourQuestion);

  // To get one specific element:
  JSONObject w1 = jObject.getJSONObject("10");
  JSONObject w2 = jObject.getJSONObject("20");

  // Iterate over all elements
  Iterator<?> keys = jObject.keys();
  while( keys.hasNext() ) {
  String key = (String)keys.next(); // "10", etc
  if ( jObject.get(key) instanceof JSONObject ) {

   try {
  // jsonString is a string variable that holds the JSON 
   JSONArray itemArray=jObject.getJSONArray(key);
   for (int i = 0; i < itemArray.length(); i++) {
     int value=itemArray.getInt(i);
     Log.e("json", i+"="+value);
    }
   } catch (JSONException e) {
   // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
 } catch (JSONException e){
  Log.e(LOG_TAG, "Failure converting JSON String", e);
  }

答案 1 :(得分:0)

好的,比我想象的要简单。只需将每个“行”作为JSONArray引用并使用列索引进行解析:

try {

    JSONObject jsonObj = new JSONObject(response);
    if(jsonObj.length() > 0){
        Iterator keys = jsonObj.keys();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            JSONArray rowArr = jsonObj.getJSONArray(key);

            String fieldone = rowArr.getString(0);
            String fieldtwo = rowArr.getString(1);           

            ...
        }
    }
} catch(e) {
    ...
}

感谢您的投入,chaps。