简体   繁体   中英

Check the Keys of an external JSON File in Java

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

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 .

  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM