How to parse Nested json using Retrofit …?

[亡魂溺海] 提交于 2021-02-08 03:47:37

问题


I don't know how to parse json using retrofit. Am familiar with parsing simple json using Retrofit but am not familiar with parsing nested Json using Retrofit.

Here is my Json data.................

  {
         "current_observation": {
             "image": {
                 "url":"http://icons.wxug.com/graphics/wu2/logo_130x80.png",                
                 "title":"Weather Underground",
                 "link":"http://www.wunderground.com"
},
                  {
                  "url":"http://icons.wxug.com/graphics/wu2/logo_130x80.png",               
                 "title":"Weather Underground",
                 "link":"http://www.wunderground.com"
                   }
             }
         }
     }

Any help will be appreciated. Thank you.

This is my method for simple json

public class Country {
    @SerializedName("current_observation")
    @Expose
    private List<Items> items;

    public List<Items> getItems() {
        return items;
    }

    public void setItems (List<Items> items) {
       this.items = items;
    }
}

Here comes.....

 public class Items {
        @SerializedName("image")
        @Expose
        private String url;
        private String title;
        private String link;

        public String getFlag() {
            return url;
        }
        public String getRank() {
           return link;
        }
        public void setRank(String link) {
            this.link = link;
        }
        public void setFlag(String url) {
            this.url = url;
        }
        public String getCountryname() {
            return title;
        }
        public void setCountryname(String rating) {
            this.title = rating;
        }
    }

Code in Main Activity

Call <Country>  call = apiInterface.getCountries();

        call.enqueue(new Callback <Country>() {
            @Override
            public void onResponse(Call<Country> call, Response<Country>  response) {
                Log.d(TAG,"onSuccess Server Response "+ response.toString());

                Log.d(TAG,"onSuccess received information "+ response.body().toString());
                List<Items> items = response.body().getItems();
                adapter = new RecAdapter(items, getContext().getApplicationContext());
                recyclerView.setAdapter(adapter);

            }

回答1:


CurrentObservation.class

public class CurrentObservation {

@SerializedName("image")
@Expose
private Image1 image;

public Image1 getImage() {
return image;
}

public void setImage(Image1 image) {
this.image = image;
}
}

Example.java

public class Example {

@SerializedName("current_observation")
@Expose
private CurrentObservation currentObservation;

public CurrentObservation getCurrentObservation() {
return currentObservation;
}

public void setCurrentObservation(CurrentObservation currentObservation) {
this.currentObservation = currentObservation;
}
}

Image1.java

public class Image1 {

@SerializedName("url")
@Expose
private String url;
@SerializedName("title")
@Expose
private String title;
@SerializedName("link")
@Expose
private String link;

public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getLink() {
return link;
}

public void setLink(String link) {
this.link = link;
}

}

To call it in main Activity

  Call<Example> ex = BaseUrlClass.getInterface().ex("whatever parameters");
    ex.enqueue(new Callback<Example>() {
        @Override
        public void onResponse(Call<Example> call, Response<Example> response) {
            Example list = response.body();

            CurrentObservation a = list.getCurrentObservation();
            List<Image1> im = a.getImage();
            for (int i = 0;i<im.size();i++){
                Image1 image1= im.get(i);
                String a = image1.getTitle();
                String b = image1.getUrl();
                String c = image1.getLink();
            }
        }

        @Override
        public void onFailure(Call<Example> call, Throwable t) {

        }
    });

Lastly in your Interface

public interface ApiUtils {

@GET("")  //whatever url
Call<Example> ex();  //or any parameter
}



回答2:


Use below Response class in Retrofit

class Response{
   @SerializedName("current_observation")
   Observation observation;
   //getters and setters
}

class Observation{
   @SerializedName("image")
   Image image;
   //getters and setters
}

class Image{
  @SerializedName("title")
  String title;
  @SerializedName("link")
  String link;
  @SerializedName("url")
  String url;
  //getters and setters
}



回答3:


This will be easier if you implement the Pojo correctly.

There are a conflict in your class and your json.

From your Country class, "current_observation" will be List<Items> items;

Then your json should be like this:

"current_observation":[
{
     "image": {
         "url":"http://icons.wxug.com/graphics/wu2/logo_130x80.png",
         "title":"Weather Underground",
         "link":"http://www.wunderground.com"
     }
},
{
     "image": {
         "url":"http://icons.wxug.com/graphics/wu2/logo_130x80.png",
         "title":"Weather Underground",
         "link":"http://www.wunderground.com"
     }
}]

Take note at the square bracket [] in case of using List. Even if only 1 item, your "current_observation" still need to have this to declare for List<T>.

I suggest you use this website: http://www.jsonschema2pojo.org/

Choose Source Type: JSON, Annotation style: Moshi (I'm using Moshi, or you can use Gson), Tick on: Make class serialiable

It will generate the correct Class for your json. The rest of your code should be correct already.

UPDATE: If after generating the class, there is no List generated, you should not use

List<Items> items = response.body().getItems();

but instead

Items items = response.body().getItems();



回答4:


For JSON Parsing you should use JASONSCHEMA2POJO convert JSON String to model class

inside your retrofit success response

 CurrentObservation observation = new CurrentObservation  ();
 JSONObject jsonObject = new JSONObject(response.body().string());
 observation = new Gson().fromJson(jsonObject.getString("current_observation"),CurrentObservation .class);

Model Class Like

public class Example {

@SerializedName("current_observation")
@Expose
private CurrentObservation currentObservation;

public CurrentObservation getCurrentObservation() {
return currentObservation;
}

 public void setCurrentObservation(CurrentObservation currentObservation) {
 this.currentObservation = currentObservation;
 }

} 



回答5:


How can i call it in main activity?

you need to call pojo class method like this

String url=getCurrentObservation().getImage().getUrl();

if you get from response

String url=response.body().getCurrentObservation().getImage().getUrl();

for more help retrofit follow this link with my ans




回答6:


i looked at your Json String in detail. just look at your "image" key followed by a JSONObject.

{
     "current_observation": {
       "image": {
             "url":"http://icons.wxug.com/graphics/wu2/logo_130x80.png",                
             "title":"Weather Underground",
             "link":"http://www.wunderground.com"
},
              {
              "url":"http://icons.wxug.com/graphics/wu2/logo_130x80.png",               
             "title":"Weather Underground",
             "link":"http://www.wunderground.com"
               }

     }
 }

since your "image" key has multiple values, it should be inside the JSONArray. so your String should look like

{
     "current_observation": {
       "image": [{
             "url":"http://icons.wxug.com/graphics/wu2/logo_130x80.png",                
             "title":"Weather Underground",
             "link":"http://www.wunderground.com"
  },
              {
              "url":"http://icons.wxug.com/graphics/wu2/logo_130x80.png",               
             "title":"Weather Underground",
             "link":"http://www.wunderground.com"
               }
         ]

     }
 }

I suggest you should check your String again.



来源:https://stackoverflow.com/questions/48580144/how-to-parse-nested-json-using-retrofit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!