Я пытаюсь вернуть список «вопросов» с тонким фреймворком и потреблять их в моем приложении 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());
}
});
Но это не правильно, потому что апи дать мне объект список и в моем приложении мне нужен массив: 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();
}
}