I would like to parse data from JSON which is of type String
.
I am using Google Gson.
I have:
jsonLine = \"
{
\"data\": {
\"translati
You can use a separate class to represent the JSON object and use @SerializedName
annotations to specify the field name to grab for each data member:
public class Response {
@SerializedName("data")
private Data data;
private static class Data {
@SerializedName("translations")
public Translation[] translations;
}
private static class Translation {
@SerializedName("translatedText")
public String translatedText;
}
public String getTranslatedText() {
return data.translations[0].translatedText;
}
}
Then you can do the parsing in your parse() method using a Gson
object:
Gson gson = new Gson();
Response response = gson.fromJson(jsonLine, Response.class);
System.out.println("Translated text: " + response.getTranslatedText());
With this approach, you can reuse the Response
class to add any other additional fields to pick up other data members you might want to extract from JSON -- in case you want to make changes to get results for, say, multiple translations in one call, or to get an additional string for the detected source language.