Home » Java » Check the Keys of an external JSON File in Java-Exceptionshub

Check the Keys of an external JSON File in Java-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

as the Title states i would like to check the Keys of an external Json File in Java.

What i tried:

JSONObject json = new JSONObject("src/com/json/inventory.json");
System.out.println(json.keys());

Issue: Doesn’t do anything.

What are other posibilities?

Thank you in advance!

EDIT
Error

How to&Answers:

If you’re using this library, first you should read the file content like:

String unparsedJson = Files.readAllLines(Paths.get("src/com/json/inventory.json"))
                .stream()
                .reduce((a,b) -> a + b)
                .get();

Then you can parse json with the code you provided:

JSONObject json = new JSONObject(unparsedJson);

And iterate over the keys with something like this:

json.keys().forEachRemaining(key -> {
            System.out.println(key);
        });

You could also use other libraries such as Jackson and Gson.

Answer:

  1. Get JSON file from Assets Folder
  2. Print all keys from JSON

private String getJSonFromAssets(){
    String json = null;
    try {
        InputStream is = getAssets().open("colorAndValue.json");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException e) {
        e.printStackTrace();
    }
    return json;
}

---

try {
        JSONObject jsonObject = new JSONObject(getJSonFromAssets());
        Iterator<String> keys = jsonObject.keys();
        while(keys.hasNext()) {
            String key = keys.next();
            System.out.println(key);
            Log.d("innerKey", "key " + key);
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

And your output will be like
1. key color0
2. key color1
3. key color2
4. key color3
5. key color4
6. key color5