0

I'm parsing a JsonObject with gson library using maven dependencies but I can not have a map containing the keys and values.

I tried with the keyset method but it does not find the correspondence with the value (null pointer exception error) the JSONArray fields reprensent the array that i want to get but currentJsonObject.get("fields") return an object that i cant parse to get the other key values. this is the result of object which i get it from the object return by get("fields")

To summarize I want to parse the JSONArray fields and retrieve the value key from this array

 JsonReader jsonReader = new JsonReader(new InputStreamReader(new FileInputStream("filename"), StandardCharsets.UTF_8));
    jsonReader.beginArray();
    Gson gson = new GsonBuilder().create();
    Collection<String> list ;
    Collection<String> keys ;
    BasicDBObject map = new BasicDBObject();

    while (jsonReader.hasNext()) {
        JSONObject currentJsonObject = gson.fromJson(jsonReader, 
    JSONObject.class);
        System.out.println(currentJsonObject.get("fields"));

        }
    jsonReader.close();

Json :

Swati
  • 28,069
  • 4
  • 21
  • 41
Dida
  • 23
  • 1
  • 7
  • You don't really need Gson here, you can simply use `JsonParser()`. – Frontear May 08 '19 at 12:43
  • i used JsonParset but the size of the file is 5GB si i tried to configue JVM and it takes 45 minutes to execute without displaying any result so tried with gson – Dida May 08 '19 at 12:46
  • can i find any other solution? – Dida May 08 '19 at 12:49
  • I've found a thread on stackoverflow which discusses performance benefits: https://stackoverflow.com/questions/43328372/fast-efficient-way-to-read-large-json-files-line-by-line-in-java – Frontear May 08 '19 at 12:50

1 Answers1

0

The below code might help you:

public String parse(String jsonLine) {
    JsonElement jelement = new JsonParser().parse(jsonLine);
    JsonObject  jobject = jelement.getAsJsonObject();
    jobject = jobject.getAsJsonObject("data");
    JsonArray jarray = jobject.getAsJsonArray("translations");
    jobject = jarray.get(0).getAsJsonObject();
    String result = jobject.get("translatedText").getAsString();
    return result;
}
DarkDuster
  • 103
  • 1
  • 10
  • It would be nice if you could add comments as to what your code does – Frontear May 08 '19 at 12:45
  • can you add some comments (where i put the method "parse" ) ? – Dida May 08 '19 at 12:48
  • @Frontear don't you think it would like spoon feeding. – DarkDuster May 08 '19 at 12:48
  • 1
    @DarkDuster not necessarily. I think giving an entire method with no understanding of how it works is far worse. You end up not learning anything. At least with some comments, OP can learn what is actually going on – Frontear May 08 '19 at 12:49