Home >Java >javaTutorial >How to Extract 'translatedText' from a JSON String Using Gson in Java?
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 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!