JSON parsing in Java using Gson

0 votes

I have the following code which I am trying to parse from JSON using Google GSON: 

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

JsonParsing class

public class JsonParsing{
   public void parse(String jsonLine) {
      // ---------Get Hello World Here-------
   }
}

How do I fetch the "Hello World" string in my class? Please help.

Nov 21, 2018 in Java by 93.lynn
• 1,560 points
423 views

1 answer to this question.

0 votes

Well, you can easily do that by avoiding the checks. Follow the below code:

 public String parse(String jsonLine) {
    JsonElement jsonEle = new JsonParser().parse(jsonLine);
    JsonObject  jsonObj = jsonEle.getAsJsonObject();
    jsonObj = jsonObj.getAsJsonObject("data");
    JsonArray jsonArr = jsonObj.getAsJsonArray("translations");
    jsonObj = jsonArr.get(0).getAsJsonObject();
    String res = jsonObj.get("translatedText").getAsString();
    return res;
}

For more info, you can refer here: Gson's javadocs.

answered Nov 21, 2018 by code.reaper12
• 3,450 points

Related Questions In Java

0 votes
2 answers

How can I create File and write data in it using Java?

import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class WriteFiles{ ...READ MORE

answered Jul 26, 2018 in Java by samarth295
• 2,190 points
91 views
0 votes
3 answers

How to parse JSON in Java

import org.json.*; JSONObject obj = new JSONObject(" .... ...READ MORE

answered Aug 20, 2018 in Java by Daisy
• 8,050 points
1,491 views
0 votes
2 answers
+14 votes
18 answers

How can I convert String to JSON object in Java?

Hi @Daisy You can use Google gson  for more ...READ MORE

answered Feb 7 in Java by Suresh
• 700 points
78,356 views
0 votes
2 answers

How to convert a JSON String into Object in Java?

You could probably check out Google's Gson: ...READ MORE

answered Aug 21 in Java by Sirajul
• 25,700 points
294 views
0 votes
1 answer

How to convert or cast hashmap to JSON object in Java, and again convert JSON object to JSON string?

You can use: new JSONObject(map); READ MORE

answered Jun 27, 2018 in Java by Akrati
• 3,150 points
1,821 views
0 votes
1 answer

How can we return a JSON object from a Java Servlet?

response.setContentType("application/json"); // Get the printwriter object from response ...READ MORE

answered Jul 6, 2018 in Java by sharth
• 3,320 points
1,579 views
0 votes
1 answer

Purpose of “String args[]” in the “psvm” of Java

Let me give you the complete explanation ...READ MORE

answered May 7, 2018 in Java by code.reaper12
• 3,450 points
87 views
0 votes
1 answer

Need for finalize() in Java

finalize() is a method called by the ...READ MORE

answered May 8, 2018 in Java by code.reaper12
• 3,450 points
73 views