如何使用Retrofit解析嵌套的JSON?

3
我不知道如何使用Retrofit解析JSON。我能够使用Retrofit解析简单的JSON,但是我不熟悉使用Retrofit解析嵌套的JSON。
以下是我的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"
                   }
             }
         }
     }

感谢您的支持。 以下是我对简单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;
        }
    }

主活动中的代码

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

            }

不需要解析JSON对象,只需在模型类中使用注释。 - Farhana Naaz Ansari
展示一下你如何处理“简单的JSON”,然后我们会建议如何修改。 - Jacky
好的,我会展示给你看。@Jacky - MilkaMozhi
你不需要在Retrofit中解析,它会返回一个列表。 - Farhana Naaz Ansari
你用我的方法解决了吗? - Adil
显示剩余5条评论
6个回答

4

Retrofit 中使用以下 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
}

谢谢兄弟......我该如何在主活动中调用它......?你能给我展示一些样例吗? - MilkaMozhi
@MilkaMozhi 这是一个示例链接 http://www.pratikbutani.com/2016/05/android-tutorial-json-parsing-using-retrofit-part-1/。希望它能帮到你。 - Chithra B
发布你的整个Json,那是一个对象还是数组? - Rajan Kali
等一下,兄弟,我会尝试。 - MilkaMozhi
我已经发布了我的整个JSON兄弟。 - MilkaMozhi

4

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

}

在主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) {

        }
    });

最后,在您的界面中。
public interface ApiUtils {

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

它报了什么错误?你尝试过调试吗? - Arpit todewale

2

如果您正确实现了Pojo,这将更容易。

您的类和json存在冲突。

根据您的Country类,“current_observation”将是List<Items> items;

那么您的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"
     }
}]

在使用List时要注意方括号[],即使只有一个项目,您的“current_observation”仍需要这个来声明>。建议您使用此网站:http://www.jsonschema2pojo.org/。选择源类型:JSON,注释样式:Moshi(我正在使用Moshi,或者您可以使用Gson),在“Make class serialiable”上打勾,它将为您的json生成正确的类。您的其余代码应该已经是正确的了。 更新:如果生成类后没有生成List,则不应使用。
List<Items> items = response.body().getItems();

但相反地

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

是的,你说得对。它是一个列表,而不是单个项目。我把它修剪了一下以简化问题。现在我已经更新了它。请仔细查看。 - MilkaMozhi
@MilkaMozhi,我的朋友,它仍然是错误的。使用JSON验证器,你就可以看到了。这就是为什么我怀疑你的JSON无法序列化为你的类的原因。 - Jacky

1
在解析JSON时,您应该使用JASONSCHEMA2POJO将JSON字符串转换为模型类。 在Retrofit成功响应中
 CurrentObservation observation = new CurrentObservation  ();
 JSONObject jsonObject = new JSONObject(response.body().string());
 observation = new Gson().fromJson(jsonObject.getString("current_observation"),CurrentObservation .class);

模型类似。
public class Example {

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

public CurrentObservation getCurrentObservation() {
return currentObservation;
}

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

} 

@MilkaMozhi 回答中哪部分很复杂? - Mahesh Vayak
抱歉,兄弟,在看到你编辑过的帖子之前我已经回复了。 - MilkaMozhi

1

我该如何在主活动中调用它?

你需要像这样调用pojo类方法

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

如果你从响应中获取
String url=response.body().getCurrentObservation().getImage().getUrl();

如果需要更多关于Retrofit的帮助,请参考这个链接和我的答案。


0

我仔细查看了你的Json字符串。只需查看你的“image”键后面的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"
               }

     }
 }

由于您的“image”键具有多个值,因此它应该在JSONArray中。因此,您的字符串应该如下所示:

{
     "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"
               }
         ]

     }
 }

我建议您再次检查您的字符串。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接