用于API的精简框架和使用Retrofit进行消费

时间:2016-03-13 12:15:26

标签: rest retrofit slim retrofit2

我尝试使用slim框架返回“问题”列表,并在我的Android应用程序中使用它进行改造。

$app->get('/questions', function() use ($app, $bdd, $logger) {

    $stmt = $bdd->prepare('SELECT * FROM questions');
    $stmt->execute();
    $questions = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $app->render(200, $questions);

});

{
  "0":{
      "id":"1",
      "userID":"1",
      "choice_1":"choice 1",
      "choice_2":"choice 2",
      "count_1":"213",
      "count_2":"165",
      "dateAdd":"2016-03-06"
   },
   "1":{
      "id":"2",
      "userID":"1",
      "choice_1":"choice 1",
      "choice_2":"choice 2",
      "count_1":"0",
      "count_2":"0",
      "dateAdd":"2016-03-04"
   },
   "error":false,
   "status":200
}

在我的改造api服务中:

@GET("questions")
Call<ArrayList<Question>> getQuestions();

并致电:

APIService api = getRetrofit().create(APIService.class);
Call<ArrayList<Question>> call = api.getQuestions();

call.enqueue(new Callback<ArrayList<Question>>() {
    @Override
    public void onResponse(Response<ArrayList<Question>> response, Retrofit retrofit) {
        questions.addAll(response.body());
    }

    @Override
    public void onFailure(Throwable t) {
        Log.d("QFragment", "loadData error" + t.getMessage());
    }
});

但是不正确,因为api给我对象列表,在我的应用程序中我需要一个数组: java.lang.IllegalStateException:预期为BEGIN_ARRAY,但在第1行第2列路径为BEGIN_OBJECT $

有些帮助吗?

RESULT

好吧,Jackub回答我解决了我的问题,只需将registerTypeAdapterFactory添加到我的GsonBuilder()中,只获得有效负载:

public class ItemTypeAdapterFactory implements TypeAdapterFactory {

  public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) {

    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
    final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);

    return new TypeAdapter<T>() {

        public void write(JsonWriter out, T value) throws IOException {
            delegate.write(out, value);
        }

        public T read(JsonReader in) throws IOException {
            JsonElement jsonElement = elementAdapter.read(in);
            if (jsonElement.isJsonObject()) {
                JsonObject jsonObject = jsonElement.getAsJsonObject();
                if (jsonObject.has("payload")) {
                    jsonElement = jsonObject.get("payload");
                }
            }

            return delegate.fromJsonTree(jsonElement);
        }
    }.nullSafe();
  }
}

1 个答案:

答案 0 :(得分:1)

因为有密钥errorstatus所以数组索引会转换为密钥。

您可以执行类似

的操作
$payload = ['payload' => $questuons];

$app->render(200, $payload);

并在Android应用中调整您对响应的消耗。