【问题标题】:Parse a nested json with retrofit 2.0使用改造 2.0 解析嵌套的 json
【发布时间】:2016-01-05 21:06:22
【问题描述】:

我有这个 json,我想使用改造来解析它们。

{
  "status": "true",
  "data": [
{
  "id": "1",
  "title": "Hi :)",
  "text": "<p>121212</p>",
  "cat_id": "1",
  "username": "admin",
  "coin": "0",
  "datetime": "1451508880",
  "isShow": "1"
},
{
  "id": "3",
  "title": " Hi :)",
  "text": "Hi :)",
  "cat_id": "2",
  "username": "Hi :)",
  "coin": "20",
  "datetime": "1451508880",
  "isShow": "1"
},
{
  "id": "4",
  "title": "a",
  "text": "someText",
  "cat_id": "1",
  "username": "admin",
  "coin": "10",
  "datetime": "1451982292",
  "isShow": "1"
}
  ]
}

当该 json 处于数组模式时,我的代码工作。但我的问题是如何像上面的示例那样解析嵌套的 json?

这里是我的 javaClass: (statusClass)

public class retroStatus {

@SerializedName("status")
private String status;

@SerializedName("data")
private ArrayList<retroPost> data;

  //getters And Setters
}

(retroPost 类)

public class retroPost {

@SerializedName("id")
private int id;

@SerializedName("title")
private String title;

@SerializedName("text")
private String text;

@SerializedName("cat_id")
private int cat_id;

@SerializedName("datetime")
private long datetime;


 //getters And Setters
}

(getPostInterface)

public interface getPost {
@GET("get/posts/all")
Call<List<retroStatus>> getPost();
}

(和主代码)

  Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://mywebsite.it/api/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    getPost postService = retrofit.create(getPost.class);
    Call<List<retroStatus>> call = postService.getPost();
    Callback<List<retroStatus>> callback = new Callback<List<retroStatus>>() {
        @Override
        public void onResponse(Response<List<retroStatus>> response, Retrofit retrofit) {
            if (response.isSuccess()) {
                for (retroStatus status : response.body()) {
                    Log.e("test", "nowStatusIs: " + status.getStatus());
                }
            } else {
                Log.e("test", "Failed");
            }


        }

        @Override
        public void onFailure(Throwable t) {
            Log.e("test", "onFailure");
        }
    };
    call.enqueue(callback);

现在当运行应用程序时,onFailure 发生了,但如果主 json 仅在 onejsonArray 中并仅使用 retroPost 进行解析,那非常好......我错了什么?
抱歉英语不好...

【问题讨论】:

    标签: android json gson retrofit


    【解决方案1】:

    您的 json 根节点不是数组,但您在接口 getPost 处将其声明为 List&lt;responseStatus&gt;。所以你需要使用responseStatus 而不是当前的。并使用gettter访问data

    @SerializedName("data")
    private ArrayList<retroPost> data;
    

    这是数组

    【讨论】:

    • 谢谢...我把它弄混了,犯了一个愚蠢的错误... :)
    【解决方案2】:

    我看到很多人都面临这个问题,所以我用 Retrofit 发布了我自己的方式,这是我所做的,它是如此简单和干净:

    创建 ServiceHelper 类:

    public class ServiceHelper {
    
    private static final String ENDPOINT = "http://test.com";
    
    private static OkHttpClient httpClient = new OkHttpClient();
    private static ServiceHelper instance = new ServiceHelper();
    private IPlusService service;
    
    
    private ServiceHelper() {
    
        Retrofit retrofit = createAdapter().build();
        service = retrofit.create(IPlusService.class);
    }
    
    public static ServiceHelper getInstance() {
        return instance;
    }
    
    private Retrofit.Builder createAdapter() {
    
        httpClient.setReadTimeout(60, TimeUnit.SECONDS);
        httpClient.setConnectTimeout(60, TimeUnit.SECONDS);
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        httpClient.interceptors().add(interceptor);
    
        return new Retrofit.Builder()
                .baseUrl(ENDPOINT)
                .client(httpClient)
                .addConverterFactory(GsonConverterFactory.create());
    }
    
    public Call<List<CategoryModel>> getAllCategory() {
        return service.getAllCategory();
    }
    

    }

    然后在我的案例中创建您的服务类 IPlusService

        public interface IPlusService {
    
        @GET("/api/category")
        Call<List<CategoryModel>> getAllCategory();
    }
    

    现在在您的 Fragment/Activity 类中,您可以使用类似这样的方式调用您自己的方法:

    ServiceHelper.getInstance().getAllCategory().enqueue(new Callback<List<CategoryModel>>() {
            @Override
            public void onResponse(Response<List<CategoryModel>> response, Retrofit retrofit) {
                processResponse(response);
            }
    
            @Override
            public void onFailure(Throwable t) {
                processResponse(null);
            }
        });
    

    还要在你的 gradle 中添加以下依赖项:

    dependencies {
    
          compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
        compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
        compile 'com.squareup.okhttp:logging-interceptor:2.6.0'
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-25
      • 1970-01-01
      • 2018-09-23
      • 2019-02-26
      • 1970-01-01
      • 1970-01-01
      • 2021-01-06
      • 2019-05-08
      相关资源
      最近更新 更多