Search code examples
javajsongson

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"

   }

}

Solution

  • 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.