Retrofit 2预计BEGIN_OBJECT但是BEGIN_ARRAY

时间:2016-03-13 21:03:39

标签: android retrofit2

我有一个看起来像这样的JSON对象:

[[{
    "customers_id": 0
    "name": "John Doe",
    "address": "1234 Merry Way",
    "city": "Miami",
    "zipcode": "55443",
    "state": "Florida"
}, {
    "customers_id": 1
    "name": "John Doe",
    "address": "1234 Merry Way",
    "city": "Miami",
    "state": "Florida"
}, {
    "customers_id": 2
    "name": "John Doe",
    "address": "1234 Merry Way",
    "city": "Miami",
    "state": "Florida"
}],[]

当Retrofit返回时,我收到错误Expected BEGIN_OBJECT but was BEGIN_ARRAY。我的呼叫设置为返回列表但是:

@POST("search_clients.php")
Call<List<Course>> GetClients();

我的实际改装电话如下:

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .build();

ClientLookup clientLookup = retrofit.create(ClientLookup.class);

Call<List<Client>> clients = clientLookup.GetClients();
clients.enqueue(new Callback<List<Client>>() {
    @Override
    public void onResponse(Response<List<Client>> response) {
        if (!response.isSuccess()) {
            Log.e(TAG, "No Success: " + response.message());
             return;
        }

        Log.d(TAG, response.body().toString());
    }

    @Override
    public void onFailure(Throwable t) {
        Log.e(TAG, "Failure: " + t.getMessage());
    }
});

最后我的模型看起来像这样:

public class Client {
  private int customers_id;
  private String name;
  private String address;
  private String city;
  private String zipcode;
  private String state;
}

最后一个自定义转换器删除前导[和尾随,[]

public final class ClientCleaner extends Converter.Factory {
    private static final String TAG = ClientCleaner.class.getName();

    @Override
    public Converter<ResponseBody, Client> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        return new Converter<ResponseBody, Client>() {
            @Override
            public Client convert(ResponseBody body) throws IOException {
                String returnValue = body.string();
                if (returnValue.startsWith("[")){
                    returnValue = returnValue.substring(1);
                }
                if (returnValue.endsWith(",[]]")){
                    returnValue = returnValue.substring(0, returnValue.length() - 4);
                }
                Log.d(TAG, returnValue);
                Gson gson = new Gson();
                return gson.fromJson(returnValue, Client.class);
            }
        };
    }


}

知道为什么我的电话仍然期待BEGIN_OBJECT?

1 个答案:

答案 0 :(得分:3)

反序列化列表不正确。有关如何使用Gson反序列化对象列表,请参阅此SO question

这应该足够了:

List<Client> videos = gson.fromJson(returnValue, new TypeToken<List<Client>>(){}.getType());