0

Regarding question Android (JSONObject) How can I loop through a flat JSON object to get each key and each value, I am using Franci Penov's answer to perform an iteration through the items of my JSON.

My problem is, when I find what I want, then I want to delete it. But how do I know if I am deleting the correct JSON Key if there maybe more than one item with same ID in a nested JSON object?

There is my code:

public JSONObject parseJSON(JSONObject json)
{
    Iterator<String> iter = json.keys();
    while (iter.hasNext())
    {
        String key = iter.next();
        if (key.equals("-xmlns:i") ||
            key.equals("-i:nil") ||
            key.equals("-xmlns:d4p1") ||
            key.equals("-i:type") ||
            key.equals("#text")) // I want to delete items with those ID strings
        {
            json.remove(key);
        }
        //Object value = json.get(key);
    }
    return json;
}
Community
  • 1
  • 1
NaN
  • 8,596
  • 20
  • 79
  • 153

1 Answers1

1

You can check if it is a JSONObject by calling optJSONObject(key), which will return null if it is not. If it is a JSONObject, you call your method parseJSON() recursively to make sure that the keys are also deleted in eventual nested Objects. If you have huge and nested data you may consider to implement this without recursion to avoid StackOverflowError

public JSONObject parseJSON(JSONObject json) {
    Iterator<String> iter = json.keys();
    while (iter.hasNext()) {
        String key = iter.next();
        JSONObject valueAsJsOnObject = json.optJSONObject(key);

        //if it is not null and therefore a valid JSONObject, call your method recursively
        if (valueAsJsOnObject != null) {
            parseJSON(valueAsJsOnObject);
        } else if (key.equals("-xmlns:i") ||
                key.equals("-i:nil") ||
                key.equals("-xmlns:d4p1") ||
                key.equals("-i:type") ||
                key.equals("#text")) // I want to delete items with those ID strings
        {
            json.remove(key);
        }
        //Object value = json.get(key);
    }
    return json;
}
Chrisport
  • 2,936
  • 3
  • 15
  • 19