James Newton
James Newton

Reputation: 7104

Getting type of value in a JSONObject in Android, to display the object's structure

In Android, JSONObject.get(key) returns the value an object. I would like to treat each value differently, depending on the type of data it contains.

In my barebones test, I have a JSON file like this in a folder named assets in the same folder as AndroidManifest.xml:

{ 
  "string": "example"
, "object": {
    "zero": 0
  , "one": 1
  , "two": 2
  }
}

This defines values of different types (string, object, integer).

In my Android app, I know that I can read in this file and convert it to a JSONObject.

try {
    AssetManager manager = context.getAssets();

    // Find the file at PROJECT_FOLDER/app/src/main/assets/myfile.json
    InputStream is = manager.open("myfile.json");

    int size = is.available();
    byte[] buffer = new byte[size];
    is.read(buffer);
    is.close();

    String jsonString = new String(buffer, "UTF-8");
    Log.d("TAG", jsonString);

    JSONObject json = new JSONObject(jsonString);

} catch (Exception ex) {
  ex.printStackTrace();
}

I also know that I can use an iterator to treat each key in the JSONObject individually.

private void dump(JSONObject json) throws JSONException {
  Iterator<String> iterator = json.keys();

  while (iterator.hasNext()) {
    String key = iterator.next();
    Object value = json.get(key);

    Log.d(key, " = "+value.toString()); // CHANGE TO GO HERE
  }
}

I would like to check if value is itself a JSONObject, and if so, call the dump() method recursively, so that I can log the structure of the entire object.


EDIT Following the input from @Michael Aaron Safyan and @royB, I now have the following dump() method.

private String dump(JSONObject json, int level) throws JSONException {
    Iterator<String> iterator = json.keys();
    String output = "";
    String padding = "";

    for (int ii=0; ii<level; ii++) {
        padding += "  ";
    }

    while (iterator.hasNext()) {
        String key = iterator.next();
        Object value = json.get(key);

        if (value instanceof JSONObject) {
            output += "\r"+key+": "+dump((JSONObject) value, level+1);
        } else {
            output += "\r"+padding+key+": "+value;
        }
    }

    return output;
}

This logs the JSONObject from my test as follows:

object:
  zero: 0
  two: 2
  one: 1
string: example

Upvotes: 1

Views: 1757

Answers (1)

royB
royB

Reputation: 12977

You can try instanceOf or try obj.optJSONObject(key) which returns jsonObject or null if the instance is not JsonObject. just notice that the code for it is:

/**
 * Returns the value mapped by {@code name} if it exists and is a {@code
 * JSONObject}, or null otherwise.
 */
public JSONObject optJSONObject(String name) {
    Object object = opt(name);
    return object instanceof JSONObject ? (JSONObject) object : null;
}  

which gives you the same as instanceOf

Upvotes: 2

Related Questions