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,610 points

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,470 points

Related Questions In Java

0 votes
1 answer

how to read csv file form sftp connection and store into string object in java code and convert into json.....post it using rest api

Hey, @Pooja, Before starting with anything you should ...READ MORE

answered May 12 in Java by Roshni
• 6,030 points
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,200 points
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,110 points
+15 votes
22 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, 2019 in Java by Suresh
• 720 points
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, 2019 in Java by Sirajul
• 58,210 points
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,170 points
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,370 points
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,470 points
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,470 points