Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Studio - Parse JSON Keys

Tags:

json

android

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?

like image 558
Phabreetion Avatar asked Jul 12 '26 11:07

Phabreetion


1 Answers

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"));
like image 141
Lino Avatar answered Jul 15 '26 01:07

Lino



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!