Home >Java >javaTutorial >How to Extract 'translatedText' from a JSON String Using Gson in Java?

How to Extract 'translatedText' from a JSON String Using Gson in Java?

Susan Sarandon
Susan SarandonOriginal
2024-12-12 12:14:34414browse

How to Extract

JSON Parsing in Java Using Gson

Query:

How to parse JSON data in string form? The specific scenario is to use Google's Gson library.

Example input:

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

Goal:

Extract "translatedText" from the given JSON string : "Hello world".

Answer:

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;
}

Points:

  • Use JsonParser to parse the JSON string.
  • Get the root JSON object and navigate to the data object.
  • Cast the data object into a JSON array.
  • Get the first JSON object in the array.
  • Get the translatedText value from this object.
  • Convert it to a string and return it.

Use of generalization:

Gson’s JavaDoc documentation is clear and helps us understand how to do more general JSON parsing.

The above is the detailed content of How to Extract 'translatedText' from a JSON String Using Gson in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn