简体   繁体   中英

How can i Parse JSONObject with gson library

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 :

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;
}

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