Retrofit 2.0 如何解析嵌套的 JSON object?

How can Retrofit 2.0 parse nested JSON object?

我们的团队决定使用 Retrofit 2.0,我正在对该库进行一些初步研究。如标题中所述,我想在我们的 Android 应用程序中通过 Retrofit 2.0 解析一些嵌套的 JSON object。

例如,here 是嵌套的 JSON object,格式为:

{
        "title": "Recent Uploads tagged android",
        "link": "https://www.flickr.com/photos/tags/android/",
        "description": "",
        "modified": "2015-10-05T05:30:01Z",
        "generator": "https://www.flickr.com/",
        "items": [
        {
            "title": ...
            "link": ...
            "media": {"m":"This is the value I want to get:)"}
            "description": ...
            "published": ...
            "author": ...
            "author_id": ...
            "tags": ...
        },
        {...},
        ...
        ]
}

我对 items 数组中的 JSON object 感兴趣。我注意到有 some posts 关于通过 Retrofit 1.X 解析嵌套 JSON objects,但是最新的 Retrofit 2.0 APIs 已经改变了很多,这令人困惑使它们适应新的 APIs.

我想到了两种可能的解决方案:

  1. 编写我自己的 JSON 转换器工厂,扩展 Converter.Factory
  2. Return String 类型的原始响应并自行解析。但根据我的初步研究,要从 Retrofit 2.0 获得原始响应并不容易。 Retrofit 2.0 似乎坚持在将响应传递给我之前将响应转换为某种东西,而 Retrofit 不提供自己的 StringConverter。 (我可能错了~)

更新: 我们实际上可以通过将 JSONElement 设置为 HTTP API 接口的 pojo 来获取原始响应,并使用 Retrofit 提供的 GSONConverter 作为转换器。

为您的模型使用 Gson 轻松解析 https://github.com/google/gson

我的助手方法:

public String toJson(Object object) {
    return gson.toJson(object);
}

public <T> T fromJson(String json, Class<T> classOfT) {
    return gson.fromJson(json, classOfT);
}

public <T> T fromJson(JsonElement jsonElement, Class<T> classOfT) {
    return gson.fromJson(jsonElement, classOfT);
}

你试过排球吗? ...我更喜欢它而不是改造,现在 google product.I 有工作示例,如果您不介意,我可以向您展示。 http://www.androidhive.info/2014/09/android-json-parsing-using-volley/

假设您完整的 JSON 看起来像

{
  "title": "Recent Uploads tagged android",
  "link": "https://www.flickr.com/photos/tags/android/",
  "description": "",
  "modified": "2015-10-05T05:30:01Z",
  "generator": "https://www.flickr.com/",
  "items": [
    {
      "member1": "memeber value",
      "member2": "member value"
    },
    {
      "member1": "memeber value",
      "member2": "member value"
    }
  ]
}

所以 Pojo 类 会是

public class MainPojo {
    private String title; 
    private String description;
    private String link;
    private String generator;
    private String modified;
    private ArrayList<Items> items;

    // Getters setters
}

public class Items {
    private String member2;
    private String member1;

    // Getters setters
}

注意:这与您的 JSON 的解决方案类似。如果 JSON 有其他键,Items.java 的成员可以更改。


Pojo 更新为新 JSON

public class Items {
    private String tags;
    private String author;
    private String title;
    private String description;
    private String link;
    private String author_id;
    private String published;
    private Media media;

    // Getters and Setters
}

public class Media {
    private String m;
    // Getters and Setters
}

以下代码将有助于获得嵌套的 json 对象和数组

例如:json

{  
    "similar_product":[  
        {  .....
}
    ],
    "options":{  
        "Blouse Length":[  
            {  "value_id":"696556",
               }

首先我们需要创建模型 class,模型 class 项名称在 json 项中是相同的,我们可以使用 @SerializedName("for exact json name")

public class Product {

       public Options options;

    public void setOptions(Options options) {
        this.options = options;
    }

    public Options getOptions() {
        return options;
    }


    // length...

    public class Options
    {
        @SerializedName("Blouse Length")
        private ArrayList<BlouseLength> blouseLengths;


        public void setBlouseLengths(ArrayList<BlouseLength> blouseLengths) {
            this.blouseLengths = blouseLengths;
        }

        public ArrayList<BlouseLength> getBlouseLengths() {
            return blouseLengths;
        }
    }



    public class BlouseLength {
        String value_id;
        public void setValue_id(String value_id) {
            this.value_id = value_id;
        }



        public String getValue_id() {
            return value_id;
        }
    }

}

创建用于改装的界面以获取 url

中的 json 项
// don't need to put values of id in retrofit 

ex:: "/api-mobile_.php?method=getProductById&pid="

只需在查询中传递 url 参数,它会自动获取 url

例如:

public interface Retrofit_Api {

    @FormUrlEncoded

    @GET("/api-mobile_.php?method=getProductById")
    Call<Product> responseproduct(@Query("pid") String pid);


}

在你的主要 class

     String pid=editid.getText().toString();


        final Retrofit adapter = new Retrofit.Builder()
                .baseUrl(Product_url)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        //Creating an object of our api interface
        Retrofit_Api api = adapter.create(Retrofit_Api.class);


        Call<Product> call = api.responseproduct(pid);


        call.enqueue(new Callback<Product>() {
            @Override
            public void onResponse(Call<Product> call, Response<Product> response) {


               ArrayList<Product.BlouseLength> p= new ArrayList(response.body().getOptions().getBlouseLengths());

Editadapter editadapter=new Editadapter(MainActivity.this,p);

                recyclerView.setAdapter(editadapter);


            }

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


                Log.d("Error", t.getMessage());
            }
        });



    }

我忘记为内部 Class 对象添加 @SerializedName@Expose 注释,添加这些注释后问题解决了。像这样:

JSON:

{"Id": 1,}

和Class成员:

@SerializedName("Id")
@Expose
private int id;