我们的团队决定使用Retrofit 2.0,并且我正在对该库进行一些初步研究。如标题中所述,我想通过Android应用中的Retrofit 2.0解析一些嵌套的JSON对象。
例如,这是一个嵌套的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": [ { "title": ... "link": ... "media": {"m":"This is the value I want to get:)"} "description": ... "published": ... "author": ... "author_id": ... "tags": ... }, {...}, ... ] }
我对items数组内的JSON对象感兴趣。我注意到有一些关于通过Retrofit 1.X解析嵌套JSON对象的文章,但是最新的Retrofit 2.0API发生了很大变化,这在将它们适应新API时会造成混淆。
items
我想到了两种可能的解决方案:
StringConverter
更新: 通过设置JSONElementHTTP API接口的pojo并使用Retrofit提供的GSONConverter作为转换器,我们实际上可以获得原始响应。
JSONElement
假设您的完整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 }