1

我正在使用 Asycntask 来处理我的服务。但是,我想使用 Retrofit 并希望在继续之前获得一些建议。我的 json 服务如下所示。它们都有一个结果 JSONObject 和数据(JSONObject 或 JSONArray)。当我查看一些教程时,它说改造适用于 GSON,我必须将我的模型转换为 GSON 格式(http://www.jsonschema2pojo.org/)。我想学习的是,我是否也应该将我的服务的这个结果部分添加到我的模型中。在使用 Asynctask 时,我正在解析结果部分,如果消息“正常”,我开始我的数据解析。如果消息不是“ok”,那么我会显示一个带有消息的警报对话框。我能得到一些建议吗?

 {
  result: {
  code: 0,
  message: "OK",
  dateTime: "20160204135212",
  },
 movie: [
  {
   name: "Movie 1",
   category: "drama"
  },
  {
   name: "Movie 2"
   category: "comedy"
  }
 ]
}
4

2 回答 2

0

似乎您需要使用拦截器。

拦截器是允许您在使用响应之前做一些工作的机制。我标记了需要添加转换逻辑的行。

  public static class LoggingInterceptor implements Interceptor {
        @Override
        public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
            Log.i("LoggingInterceptor", "inside intercept callback");
            Request request = chain.request();
            long t1 = System.nanoTime();
            String requestLog = String.format("Sending request %s on %s%n%s",
                    request.url(), chain.connection(), request.headers());
            if (request.method().compareToIgnoreCase("post") == 0) {
                requestLog = "\n" + requestLog + "\n" + bodyToString(request);
            }
            Log.d("TAG", "request" + "\n" + requestLog);
            com.squareup.okhttp.Response response = chain.proceed(request);
            long t2 = System.nanoTime();

            String responseLog = String.format("Received response for %s in %.1fms%n%s",
                    response.request().url(), (t2 - t1) / 1e6d, response.headers());

            String bodyString = response.body().string();

            Log.d("TAG", "response only" + "\n" + bodyString);

            Log.d("TAG", "response" + "\n" + responseLog + "\n" + bodyString);

           // HERE YOU CAN ADD JSON DATA TO EXISTING RESPONSE

            return response.newBuilder()
                    .body(ResponseBody.create(response.body().contentType(), bodyString))
                    .build();

        }


        public static String bodyToString(final Request request) {
            try {
                final Request copy = request.newBuilder().build();
                final Buffer buffer = new Buffer();
                copy.body().writeTo(buffer);
                return buffer.readUtf8();
            } catch (final IOException e) {
                return "did not work";
            }
        }
    }
于 2016-02-04T12:39:01.460 回答
0

是的,您的服务的此响应应该是您应用中的模型。Retrofit 会自动将 json 序列化为 java 对象onResponse

@Override
public void onResponse(Response<Result> response){
    if(response.isSuccess()){
    Result result = response.body();
    if(result.getMessage().equals("OK")){
       //do something 
    }else{
       //show an alert dialog with message
    }
}
于 2016-02-04T20:39:11.300 回答