I would like to parse JSON using Gson.

Asked 1 years ago, Updated 1 years ago, 106 views

I want to parse JSON data expressed as a string. I'm using Google Gson.

JSON data:

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

Class you want to implement:

public class JsonParsing{

   public void parse(String jsonLine) {

      // // there I would like to get String "Hello world"

   }

}

gson java json

2022-09-21 14:46

1 Answers

It's simple: The code below is simply the main part and all exceptions are omitted.

 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").toString();
    return result;
}

For more generalization, see Gson's javadoc.


2022-09-21 14:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.