Q: Parsing JSON Data as a String with Gson
Given a JSON string jsonLine, the task is to extract the text "Hello world" using the Gson library. The provided class, JsonParsing, contains a parse method that should accomplish this task.
A: Gson's Facile JSON Parsing
The following code snippet demonstrates how to parse the JSON string using Gson:
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; }
This code sequence parses the JSON string, navigating through the nested objects and arrays to retrieve the desired text. For clarity, exception handling and input validation have been omitted.
Gson's JavaDoc provides comprehensive documentation for further exploration of its capabilities.
The above is the detailed content of How to Extract 'Hello world' from a JSON String Using Gson in Java?. For more information, please follow other related articles on the PHP Chinese website!