JSON parsing using Gson for Java

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

提交回复
热议问题