JSON parsing using Gson for Java

前端 未结 11 2257
青春惊慌失措
青春惊慌失措 2020-11-22 04:57

I would like to parse data from JSON which is of type String. I am using Google Gson.

I have:

jsonLine = \"
{
 \"data\": {
  \"translati         


        
11条回答
  •  终归单人心
    2020-11-22 05:32

    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.

提交回复
热议问题