JSON parsing using Gson for Java

前端 未结 11 2259
青春惊慌失措
青春惊慌失措 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:27

    One line code:

    System.out.println(new Gson().fromJson(jsonLine,JsonObject.class).getAsJsonObject().get("data").getAsJsonObject().get("translations").getAsJsonArray().get(0).getAsJsonObject().get("translatedText").getAsString());
    
    0 讨论(0)
  • 2020-11-22 05:28

    Using Gson to Solve
    I would create a class for individual parameter in the json String. Alternatively you can create one main class called "Data" and then create inner classes similarly. I created separate classes for clarity.

    The classes are as follows.

    • Data
    • Translations
    • TranslatedText

    In the class JsonParsing the method "parse" we call gson.fromJson(jsonLine, Data.class) which will convert the String in java objects using Reflection.

    Once we have access to the "Data" object we can access each parameter individually.

    Didn't get a chance to test this code as I am away from my dev machine. But this should help.

    Some good examples and articles.
    http://albertattard.blogspot.com/2009/06/practical-example-of-gson.html
    http://sites.google.com/site/gson/gson-user-guide

    Code

    public class JsonParsing{
    
           public void parse(String jsonLine) {
    
               Gson gson = new GsonBuilder().create();
               Data data = gson.fromJson(jsonLine, Data.class);
    
               Translations translations = data.getTranslation();
               TranslatedText[] arrayTranslatedText = translations.getArrayTranslatedText(); //this returns an array, based on json string
    
               for(TranslatedText translatedText:arrayTranslatedText )
               {
                      System.out.println(translatedText.getArrayTranslatedText());
               }
           }
    
        }
    
    
        public class Data{
               private  Translations translations;
              public Translations getTranslation()
              {
                 return translations;
              }
    
              public void setTranslation(Translations translations)
               {
                      this.translations = translations;
               }
        }
    
        public class Translations
        {
            private  TranslatedText[] translatedText;
             public TranslatedText[] getArrayTranslatedText()
             {
                 return translatedText;
             }
    
               public void setTranslatedText(TranslatedText[] translatedText)
               {
                      this.translatedText= translatedText;
               }
        }
    
        public class TranslatedText
        {
            private String translatedText;
            public String getTranslatedText()
            {
               return translatedText;
            }
    
            public void setTranslatedText(String translatedText)
            {
               this.translatedText = translatedText;
            }
        }
    
    0 讨论(0)
  • 2020-11-22 05:28

    Firstly Generate Getter And Setter using below parsing site

    http://www.jsonschema2pojo.org/

    Now use Gson

    GettetSetterClass object=new Gson().fromjson(jsonLine,GettetSetterClass.class);
    

    Now use object to get values such as data,translationText

    0 讨论(0)
  • 2020-11-22 05:32

    This is simple code to do it, I avoided all checks but this is the main idea.

     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;
    }
    

    To make the use more generic - you will find that Gson's javadocs are pretty clear and helpful.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题