0

Before I parse json json array, but this json object. Its It drove me to a standstill. How i can parse json like this:

 { "test1": {
            "1": {
                "action": "0",
                "type": "1",
                "id": "1",
            },
            "2": {
                "action": "0",
                "type": "1",
                "id": "2",
            }
        },
        "test2": {
            "1": {
                "id": "1",
                "name": "one"
            },
            "2": {
                "id": "2",
                "name": "two"
            },
            "5": {
                "id": "5",
                "name": "three"
            }
        }}
Blackbelt
  • 156,034
  • 29
  • 297
  • 305
ntj23061
  • 13
  • 1

2 Answers2

2

When you don't have a fixed set of keys, that you know upfront, the only way to parse it is to use keys(). It returns an Iterator with the keys contained in the JSONObject. In your case you could have

JSONObject jsonObject = new JSONObject(...);
Iterator<String> iterator = jsonObject.keys();
while(iterator.hasNext()) {
  String currentKey = iterator.next();
  JSONObject obj = jsonObject.optJSONObject(key); 
  if (obj != null) {
     Iterator<String> iterator2 = obj.keys();

  }
}

iterator will return test1 and test2, while iterator2 will return 1 and 2, for test1 and 1 ,2 , 5 for test2

Blackbelt
  • 156,034
  • 29
  • 297
  • 305
0

You can create a JSONObject From string as bellow

JSONObject jsonObject = new JSONObject(YOUR_JSON_STRING);

and to parse the jsonObject

JSONObject test1Json = jsonObject.getJSONObject("test1");
JSONObject oneTest1Json = test1Json.getJSONObject("1");

to get String values

String action = oneTest1Json.getString("action");
String type = oneTest1Json.getString("type");
String id = oneTest1Json.getString("id");
Log.d("Json parse","action -"+action+" type -"+type+" id -"+id);

if need them as JSONArray the you can try

public JSONArray getJsonArray (JSONObject jsonObject){
    JSONArray nameJsonArray = jsonObject.names();
    JSONArray jsonArray = new JSONArray();
    for (int i = 0; i < nameJsonArray.length(); i++) {
        try {
            String key = nameJsonArray.getString(i);
            jsonArray.put(jsonObject.getString(key));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return jsonArray;
}

in case keys like test1,test2,test3...

    JSONObject jsonObject = new JSONObject("{'test1':'Kasun', 'test2':'columbo','test3': '29'}");
    JSONArray jsonArray = new JSONArray();
    for (int i = 1; i <= jsonObject.names().length(); i++) {
        try{
            jsonArray.put(jsonObject.getString("test" + i));
        }catch (JSONException e){
            e.printStackTrace();
        }

you can get your JSONArray this way.

Shabeer Ali
  • 903
  • 11
  • 20