获取JSON左侧值

时间:2018-12-11 08:41:14

标签: android arrays json

我想获取数字“ 10449479”,“ 10449480”,“ 10449481”。

{
"xyz": {
"10449479": {
  "a": "22",
  "b": "33",
  "c": " - "
},
"10449480": {
  "a": "44",
  "b": "55",
  "c": " - "
  },
"10449481": {
  "a": "66",
  "b": "77",
  "c": " - "
 }}}

我需要获取keys(),因为它们是unknown。我如何获得这些数字。请帮忙。

public void onResponse(JSONObject response) {//From Volley

    try {
        JSONObject jarray = response.getJSONObject("xyz");

        Iterator<String> iter = jarray.keys();
        while (iter.hasNext()) {
            String key = iter.next();
            try {
                Object value = jarray.get(key);

            } catch (JSONException e) {
                // Something went wrong!
            }
        }


    } catch (JSONException e) {
        e.printStackTrace();


    }

}

我只能在每个键之内获取嵌套值,例如

{
  "a": "22",
  "b": "33",
  "c": " - "
}
//and other 2

如何获取左侧键。谢谢。

1 个答案:

答案 0 :(得分:0)

如果键是动态的,则可以使用jsonobj.keys()

进行迭代
JSONObject JSONObj = new JSONObject(your_json_string);

// get all keys from json object
Iterator<String> iterator = JSONObj.keys();

while (iterator.hasNext()) {
    String key = iterator.next();
    Log.i("TAG","key:"+key +"--Value::"+JSONObj.optString(key);
}