【问题标题】:How to consume this JSON structure via Retrofit 2?如何通过 Retrofit 2 使用这个 JSON 结构?
【发布时间】:2016-06-23 22:33:07
【问题描述】:

您好,我有一个 json 结构,我需要从 url 获取数据。我怎样才能做到这一点?什么是类和函数。请帮我。谢谢。

这是我的 json。

{
nodes: [
{
node: {
title: "...",
field_news_image: [
{title="..."},
{title="..."},
{title="..."},
{title="..."},
{title="..."},
{title="..."},
{title="..."}
],
body: "...",
field_category: "...",
created: "..."
}
},
{
node: {
title: "...",
field_news_image: [
{title="..."},
{title="..."},
{title="..."},
{title="..."},
{title="..."}
],
body: "...",
field_category: "...",
created: "..."
}
}
]
}

【问题讨论】:

    标签: android json retrofit


    【解决方案1】:

    使用 jsonschema2pojo.org 粘贴你的响应,它会为你生成 Java 类。 您可以通过设置所有必要的组件来实例化 Retrofit 实例,如下所示:

    Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BuildConfig.BASE_URL)
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .build();
    

    您的界面将如下所示:

    @GET("api/service/schedule/{filial}")
        Observable<Response<List<Event>>> getSchedule(@Path("filial") String filial);
    

    其中@GET-注解定义请求类型, Response - Retrofit 使用的类型,携带响应是否成功的信息(参见类方法)。 Observable - 来自 rxJava 库的类型,允许以反应方式处理请求。 我强烈推荐使用 RxJava,因为它极大地简化了后台执行。 (不要使用 AsyncTasks!!)。

    为了使用 Retrofit2 在你的 Gradle 文件中添加以下行:

       //Reactive programming
        compile 'io.reactivex:rxjava:1.1.5'
        compile 'io.reactivex:rxandroid:1.2.0'
    
    
        compile 'com.google.code.gson:gson:2.4'
        //retrofit and okhttp
        compile 'com.squareup.okhttp3:okhttp:3.2.0'
        compile 'com.squareup.retrofit2:retrofit:2.0.2'
        compile 'com.squareup.retrofit2:converter-gson:2.0.2'
        compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
    

    您将通过类似的调用实例化 Retrofit2 接口: 改造.create(Api.class)

    【讨论】:

    • 我的改装接口呢?
    【解决方案2】:

    http://www.jsonschema2pojo.org/

    将您的 JSON 响应放在这里并从该网站下载 java 代码。然后把这个java代码放到你的项目中并使用它。该网站将制作所有必填类以及所有必填字段,非常适合您对 JSON 的响应。我用过很多次了,肯定能用。

    http://square.github.io/retrofit/在这里您可以获取有关如何使用改造来 POST 或 GET 数据的详细信息。

    Retrofit 将您的 HTTP API 转换为 Java 接口。

    public interface YourService {
      @GET("users/{user}/repos")
      Call<List<Repository>> listRepos(@Path("user") String user);
    }
    

    Retrofit 类生成接口的实现。

    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://api.yourAPI.com/")
        .build();
    
    YourService  service = retrofit.create(YourService .class);
    
    Call<List<Repository>> repos = service.listRepos("myrepository");
    

    使用注解来描述HTTP请求:

    • URL 参数替换和查询参数支持对象 转换为请求正文(例如 JSON、协议缓冲区) 多部分 请求正文和文件上传

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 2017-06-08
      • 1970-01-01
      • 2013-05-13
      • 1970-01-01
      相关资源
      最近更新 更多