使用改进2.0解析嵌套的json

时间:2016-01-05 21:06:23

标签: android json gson retrofit

我有这个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 Class)

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

(和mainCode)

  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来解析那些工作非常好......我错了什么?
抱歉英语不好......

2 个答案:

答案 0 :(得分:4)

json的根节点不是数组,但是您在接口List<responseStatus>处将其声明为getPost。因此,您需要使用responseStatus而不是当前的data。并使用gettter访问@SerializedName("data") private ArrayList<retroPost> data;

TLS_DHE_DSS_WITH_AES_128_CBC_SHA

是数组

答案 1 :(得分:2)

我看到很多人都面临这个问题,所以我用自己的方式发布了改造,这就是我所做的事情,这么简单干净:

创建 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'

}
相关问题