0

Q.1 Reading JSON Suppose I have a JSON file that has 200K properties in its root. How can I get the value from its key without loading the whole JSON into memory? and what if there are nested nodes instead of direct properties.

For example:

{
  "contributor": {
    "Anas": {
      "github": "@anas43950",
      "website": "x-code.ml",
      "instagram": "anas.ansari46"
    },
    "Shubam": {
      "github": "@shubhamp98",
      "website": "shubhamp98.github.io",
      "instagram": "@weshubh"
    },
    "Rahil": {
      "github": "@ErrorxCode",
      "website": "xcoder.tk",
      "instagram": "@x__coder__x"
    }
     .... // goes on
     ....  // there are 'n' users
  }
}

How can I get "Rahil" object without reading whole 'contributor' node ?

Q.2 Modifying JSON How can I change the website of 'Rahil' without reading or writing the whole JSON into memory or with the help of streaming ?

ʀᴀʜɪʟ
  • 235
  • 1
  • 4
  • 8
  • 2
    Hi, checkout [this](https://stackoverflow.com/questions/25064773/working-with-json-streams-efficiently-in-java) and [this](https://javaee.github.io/tutorial/jsonp004.html) - the key to search is "java json streaming" – Nikos Paraskevopoulos Mar 30 '22 at 11:58
  • @NikosParaskevopoulos That answers the Q.1 but not Q.2 i.e How can we edit the property of JSON using `JsonGenerator`? – ʀᴀʜɪʟ Mar 31 '22 at 08:20

1 Answers1

0

Use Gson JsonReader class which is a pull based streaming JSON parser. It helps in reading a JSON as a stream of tokens https://mvnrepository.com/artifact/com.google.code.gson/gson/1.7.1

private static void readJson() throws IOException {
    String str = "{\"message\":\"Hi\",\"place\":{\"name\":\"World!\"}}";
    InputStream in = new ByteArrayInputStream(str.getBytes(Charset.forName("UTF-8")));
    JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
    while (reader.hasNext()) {
        JsonToken jsonToken = reader.peek();
        if(jsonToken == JsonToken.BEGIN_OBJECT) {
            reader.beginObject();
        } else if(jsonToken == JsonToken.END_OBJECT) {
            reader.endObject();
        } if(jsonToken == JsonToken.STRING) {
            System.out.print(reader.nextString() + " "); // print Hi World!
        } else {
            reader.skipValue();
        }
    }
    reader.close();
}