JSON parsing using Gson for Java

375,356

Solution 1

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.

Solution 2

In my first gson application I avoided using additional classes to catch values mainly 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")
    );

Solution 3

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;

Solution 4

You can create corresponding java classes for the json objects. The integer, string values can be mapped as is. Json can be parsed like this-

Gson gson = new GsonBuilder().create(); 
Response r = gson.fromJson(jsonString, Response.class);

Here is an example- http://rowsandcolumns.blogspot.com/2013/02/url-encode-http-get-solr-request-and.html

Solution 5

One way would be created a JsonObject and iterating through the parameters. For example

JsonObject jobj = new Gson().fromJson(jsonString, JsonObject.class);

Then you can extract bean values like:

String fieldValue = jobj.get(fieldName).getAsString();
boolean fieldValue = jobj.get(fieldName).getAsBoolean();
int fieldValue = jobj.get(fieldName).getAsInt();

Hope this helps.

Share:
375,356

Related videos on Youtube

Martynas
Author by

Martynas

Updated on December 13, 2020

Comments

  • Martynas
    Martynas over 3 years

    I would like to parse data from JSON which is of type String. I am using Google Gson.

    I have:

    jsonLine = "
    {
     "data": {
      "translations": [
       {
        "translatedText": "Hello world"
       }
      ]
     }
    }
    ";
    

    and my class is:

    public class JsonParsing{
    
       public void parse(String jsonLine) {
    
          // there I would like to get String "Hello world"
    
       }
    
    }
    
  • MByD
    MByD about 13 years
    JsonObject extends JsonElement, so it is both.
  • Mike Samuel
    Mike Samuel about 13 years
    Don't you need some setters on those helper classes? Nothing can set the private String translatedText without violating access control, so there's no way fromJSON could set it in JVMs that have not opted-into reflection trampling all over access control.
  • kensen john
    kensen john about 13 years
    @Mike Samuel shoot completely forgot about the Setters
  • Illegal Argument
    Illegal Argument almost 10 years
    the first line throws cannot instantiate of the type JsonParser on version gson-2.2.4.jar
  • StaxMan
    StaxMan about 9 years
    Then your object structure is NOT matching JSON.
  • user1165560
    user1165560 over 8 years
    String result = jobject.get("translatedText").toString(); This results will include the double quotes. String result = jobject.get("translatedText").getAsString(); doesn't include the quotes.
  • tricknology
    tricknology over 7 years
    Al I the only one who thinks Gson overcomplicates things 98% of the time? A simple JSONObject would do, but we all hate try/catch that much?
  • Mason Wang
    Mason Wang almost 7 years
    I need to use the parser class, however, I am getting the MalformedJsonException, so I have to be able to do SetLeinient with JsonParser. How?
  • Minkyu Kim
    Minkyu Kim over 2 years
    @IllegalArgument It deprecated. No need to instantiate this class, use the static methods instead as JsonParser.parse(jsonString);

Related