简体   繁体   English

如何使用 Retrofit 解析嵌套的 json ...?

[英]How to parse Nested json using Retrofit …?

I don't know how to parse json using retrofit .我不知道如何使用 retrofit 解析 json Am familiar with parsing simple json using Retrofit but am not familiar with parsing nested Json using Retrofit .熟悉使用 Retrofit 解析简单的 json 但不熟悉使用Retrofit解析嵌套的 Json

Here is my Json data.................这是我的 Json 数据.......

  {
         "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这是我的简单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);

            }

Use below Response class in RetrofitRetrofit使用以下Response

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
}

CurrentObservation.class 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例子.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图像1.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
}

This will be easier if you implement the Pojo correctly.如果您正确实施 Pojo,这将更容易。

There are a conflict in your class and your json.您的班级和您的 json 存在冲突。

From your Country class, "current_observation" will be List<Items> items;从您的 Country 类中,“current_observation”将是List<Items> items;

Then your json should be like this:那么你的 json 应该是这样的:

"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.如果使用 List,请注意方括号[] Even if only 1 item, your "current_observation" still need to have this to declare for List<T> .即使只有 1 个项目,您的"current_observation"仍然需要为List<T>声明这个。

I suggest you use this website: http://www.jsonschema2pojo.org/我建议你使用这个网站: 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选择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.它将为您的 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();

For JSON Parsing you should use JASONSCHEMA2POJO convert JSON String to model class对于 JSON 解析,您应该使用JASONSCHEMA2POJO将 JSON 字符串转换为模型类

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

} 

How can i call it in main activity?我如何在主要活动中调用它?

you need to call pojo class method like this你需要像这样调用 pojo 类方法

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如需更多帮助改造,请点击此链接与我的 ans

i looked at your Json String in detail.我详细查看了您的 Json 字符串。 just look at your "image" key followed by a JSONObject.只需查看您的“图像”键,然后是 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.由于您的“图像”键有多个值,因此它应该在 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.我建议你应该再次检查你的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM