[java] JSON parsing using Gson for Java

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"

   }

}

This question is related to java json gson

The answer is


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")
    );

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


One line code:

System.out.println(new Gson().fromJson(jsonLine,JsonObject.class).getAsJsonObject().get("data").getAsJsonObject().get("translations").getAsJsonArray().get(0).getAsJsonObject().get("translatedText").getAsString());

Firstly generate getter and setter using below parsing site

http://www.jsonschema2pojo.org/

Now use Gson

GettetSetterClass object=new Gson().fromjson(jsonLine, GettetSetterClass.class);

Now use object to get values such as data,translationText


You can use a separate class to represent the JSON object and use @SerializedName annotations to specify the field name to grab for each data member:

public class Response {

   @SerializedName("data")
   private Data data;

   private static class Data {
      @SerializedName("translations")
      public Translation[] translations;
   }

   private static class Translation {
      @SerializedName("translatedText")
      public String translatedText;
   }

   public String getTranslatedText() {
      return data.translations[0].translatedText;
   }
}

Then you can do the parsing in your parse() method using a Gson object:

Gson gson = new Gson();
Response response = gson.fromJson(jsonLine, Response.class);

System.out.println("Translated text: " + response.getTranslatedText());

With this approach, you can reuse the Response class to add any other additional fields to pick up other data members you might want to extract from JSON -- in case you want to make changes to get results for, say, multiple translations in one call, or to get an additional string for the detected source language.


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.


    JsonParser parser = new JsonParser();
    JsonObject jo = (JsonObject) parser.parse(data);
    JsonElement je = jo.get("some_array");

    //Parsing back the string as Array
    JsonArray ja = (JsonArray) parser.parse(o.get("some_array").getAsString());
    for (JsonElement jo : ja) {
    JsonObject j = (JsonObject) jo;
        // Your Code, Access json elements as j.get("some_element")
    }

A simple example to parse a JSON like this

{ "some_array" : "[\"some_element\":1,\"some_more_element\":2]" , "some_other_element" : 3 }


You can use a JsonPath query to extract the value. And with JsonSurfer which is backed by Gson, your problem can be solved by simply two line of code!

    JsonSurfer jsonSurfer = JsonSurfer.gson();
    String result = jsonSurfer.collectOne(jsonLine, String.class, "$.data.translations[0].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;

Using Gson to Solve
I would create a class for individual parameter in the json String. Alternatively you can create one main class called "Data" and then create inner classes similarly. I created separate classes for clarity.

The classes are as follows.

  • Data
  • Translations
  • TranslatedText

In the class JsonParsing the method "parse" we call gson.fromJson(jsonLine, Data.class) which will convert the String in java objects using Reflection.

Once we have access to the "Data" object we can access each parameter individually.

Didn't get a chance to test this code as I am away from my dev machine. But this should help.

Some good examples and articles.
http://albertattard.blogspot.com/2009/06/practical-example-of-gson.html
http://sites.google.com/site/gson/gson-user-guide

Code

public class JsonParsing{

       public void parse(String jsonLine) {

           Gson gson = new GsonBuilder().create();
           Data data = gson.fromJson(jsonLine, Data.class);

           Translations translations = data.getTranslation();
           TranslatedText[] arrayTranslatedText = translations.getArrayTranslatedText(); //this returns an array, based on json string

           for(TranslatedText translatedText:arrayTranslatedText )
           {
                  System.out.println(translatedText.getArrayTranslatedText());
           }
       }

    }


    public class Data{
           private  Translations translations;
          public Translations getTranslation()
          {
             return translations;
          }

          public void setTranslation(Translations translations)
           {
                  this.translations = translations;
           }
    }

    public class Translations
    {
        private  TranslatedText[] translatedText;
         public TranslatedText[] getArrayTranslatedText()
         {
             return translatedText;
         }

           public void setTranslatedText(TranslatedText[] translatedText)
           {
                  this.translatedText= translatedText;
           }
    }

    public class TranslatedText
    {
        private String translatedText;
        public String getTranslatedText()
        {
           return translatedText;
        }

        public void setTranslatedText(String translatedText)
        {
           this.translatedText = translatedText;
        }
    }

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to gson

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $ Gson library in Android Studio how to parse JSON file with GSON Convert Map to JSON using Jackson "Expected BEGIN_OBJECT but was STRING at line 1 column 1" Representing null in JSON Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 How to parse JSON Array (Not Json Object) in Android Parsing JSON array into java.util.List with Gson Using GSON to parse a JSON array