2016-03-13 34 views
1

我嘗試返回列表的「問題」與苗條的框架,並消費他們在我的Android應用程序與改造。超薄框架的API和消費與改造

$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但BEGIN_OBJECT位於第1行第2列路徑$

一些幫助?


結果

好了,所以有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

這是因爲有鑰匙errorstatus,所以數組索引被轉換成密鑰。

你可以做這樣的事情

$payload = ['payload' => $questuons]; 

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

和適應您的Android應用程序的響應消費。