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"
}
}
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.
© 2024 OneMinuteCode. All rights reserved.