Android:动态访问所有嵌套的JSON对象

时间:2018-01-24 13:40:42

标签: android json

我已经检查过SO中的几乎所有帖子,但我没有得到解决方案

问题:我的JSON如下所示

{
  "address": {
    "state": "World",
    "address": "infinite space, 000",
    "city": "Android city",
    "address2": {
      "state": "World2",
      "address": "infinite space2, 002",
      "city": "Android city2",
      "address3": {
        "state": "World3",
        "address": "infinite space3, 003",
        "city": "Android city3"
      }
    }
  },
  "valid": {
    "state": "World",
    "address": "infinite space, 000",
    "city": "Android city",
    "valid2": {
      "state": "World2",
      "address": "infinite space2, 002",
      "city": "Android city2",
      "valid3": {
        "state": "World3",
        "address": "infinite space3, 003",
        "city": "Android city3"
      }
    }
  }
}

在此,每个对象名称都是唯一的,将来我也可能有许多嵌套的JSON对象。

我的要求是:我想动态解析每个嵌套的JSON对象。

例如:如果我传递任何对象名称。我的方法必须返回该对象的每个数据(键和值)或从JSON中提取每个嵌套对象并保持它们超级

2 个答案:

答案 0 :(得分:0)

最好的选择是与班级合作,而不是与Json Objec合作。我建议您使用Gson Library将json响应转换为Class

Gson https://github.com/google/gson

如果您向服务器发出请求,Gson + Retrofit 2也是很好的选择。

改造2 http://square.github.io/retrofit/

答案 1 :(得分:0)

谢谢DroiDev和MohamedMohaideenAH。最后我得到了解决方案

private void parseJson(JSONObject jsonObject){

    try {

        for(int i = 0; i < jsonObject.length(); i++){


            if(jsonObject.get(jsonObject.names().getString(i)) instanceof JSONObject){

                Log.e("===Start===", "===Start===");

                Log.e("objectName", jsonObject.names().getString(i));

                JSONObject  singleObj = new JSONObject(jsonObject.get(jsonObject.names().getString(i)).toString());

                Iterator<String> keys= singleObj.keys();
                while (keys.hasNext()){
                    String keyValue = keys.next();
                    String valueString = singleObj.getString(keyValue);

                    if(!isJSONObjectOrString(valueString))
                        Log.e(keyValue, valueString);
                }

                Log.e("===End===", "===End===");

                parseJson(singleObj);
            }
        }

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

}

private boolean isJSONObjectOrString(String str) {
    try {
        new JSONObject(str);
    } catch (JSONException e) {
        //e.printStackTrace(); //If you uncomment, log will confuse you
        return false;//If string
    }
    return true;//If JSONObject
}