Fabrizio Formichelli Fabrizio Formichelli - 3 months ago 12
Android Question

Android Studio - Parse JSON Keys

I am trying to parse a local json file. With the code I have so far I can read all the json however, I cannot return each individual key.

Json file (level.json)

{
"level1": {
"artist": "aaaa",
"title":"new title",
"year":"1990"
},
"level2": {
"artist": "bbb",
"title":"new title2",
"year":"1992"
}

}


What I am trying to do is to get for each level the key. For example I want to get "artist" from "level1".

public String loadJSONFromAsset() {
String json = null;
try {

InputStream is = getAssets().open("level.json");

int size = is.available();

byte[] buffer = new byte[size];

is.read(buffer);

is.close();

json = new String(buffer, "UTF-8");


} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;

}


When I print the function I get all the json.

JSONObject object = new JSONObject();
text.setText(object.getString("level1"));


How can I get the keys depending of each json object?

Answer

You can use for instance:

JSONObject object = new JSONObject(your_json_string);
JSONObject level1 = object.getJSONObject("level1");
JSONObject level2 = object.getJSONObject("level2");

and now you can access artist, title and year like that:

text.setText(level1.getString("artist"));
text.setText(level1.getString("title"));
text.setText(level1.getString("year"));
Comments