JSON parsing using Gson for Java JSON parsing using Gson for Java java java

JSON parsing using Gson for Java


This is simple code to do it, I avoided all checks but this is the main idea.

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

To make the use more generic - you will find that Gson's javadocs are pretty clear and helpful.


In my first gson application I avoided using additional classes to catch valuesmainly because I use json for config matters

despite the lack of information (even gson page), that's what I found and used:

starting from

Map jsonJavaRootObject = new Gson().fromJson("{/*whatever your mega complex object*/}", Map.class)

Each time gson sees a {}, it creates a Map (actually a gson StringMap )

Each time gson sees a '', it creates a String

Each time gson sees a number, it creates a Double

Each time gson sees a [], it creates an ArrayList

You can use this facts (combined) to your advantage

Finally this is the code that makes the thing

        Map<String, Object> javaRootMapObject = new Gson().fromJson(jsonLine, Map.class);    System.out.println(        (            (Map)            (                (List)                (                    (Map)                    (                        javaRootMapObject.get("data")                    )                 ).get("translations")            ).get(0)        ).get("translatedText")    );


Simplest thing usually is to create matching Object hierarchy, like so:

public class Wrapper {   public Data data;}static class Data {   public Translation[] translations;}static class Translation {   public String translatedText;}

and then bind using GSON, traverse object hierarchy via fields. Adding getters and setters is pointless for basic data containers.

So something like:

Wrapper value = GSON.fromJSON(jsonString, Wrapper.class);String text = value.data.translations[0].translatedText;