如何修复预期BEGIN_OBJECT但在改造中被STRING修复?

时间:2018-10-22 06:30:41

标签: java android json retrofit2

在我的应用程序中,我想使用 Retrofit 从服务器获取一些数据。
我在下面编写代码,但是在运行应用程序并调用api时,在错误:

下面显示给我
E/socketLogResponse: Err : com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

请参阅我上面的代码并为我提供帮助

服务器的API响应:

{
    "status": "ok",
    "time": 0.014972925186157227
}

ApiService界面:

@POST("api/log")
    Call<SocketPingResponse> getSocketPingLog(@Header("jwt") String jwt, @Body SocketPingBodySendData socketPingBodySendData);

SocketPingResponse类:

public class SocketPingResponse {
    @SerializedName("status")
    @Expose
    private String status;
    @SerializedName("time")
    @Expose
    private Double time;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Double getTime() {
        return time;
    }

    public void setTime(Double time) {
        this.time = time;
    }
}

SocketPingBodySendData类:

public class SocketPingBodySendData {
    @SerializedName("auction_id")
    @Expose
    int auction_id;
    @SerializedName("data")
    @Expose
    List<SocketPingEntity> data;

    public int getAuction_id() {
        return auction_id;
    }

    public void setAuction_id(int auction_id) {
        this.auction_id = auction_id;
    }

    public List<SocketPingEntity> getData() {
        return data;
    }

    public void setData(List<SocketPingEntity> data) {
        this.data = data;
    }
}
活动中的

Api呼叫代码:

pingEntityList.addAll(socketPingDatabase.socketPingDao().getSocketPingEntityList());
                        SocketPingBodySendData pingBodySendData = new SocketPingBodySendData();
                        pingBodySendData.setAuction_id(auctionID);
                        pingBodySendData.setData(pingEntityList);
                        Toast.makeText(context, ""+pingEntityList.size(), Toast.LENGTH_SHORT).show();
                        Call<SocketPingResponse> pingResponseCall = apis.getSocketPingLog(jwtToken, pingBodySendData);
                        pingResponseCall.enqueue(new Callback<SocketPingResponse>() {
                            @Override
                            public void onResponse(Call<SocketPingResponse> call, Response<SocketPingResponse> response) {
                                    if (response.body() != null) {
                                        Toast.makeText(context, response.body().getStatus(), Toast.LENGTH_SHORT).show();
                                        if (response.body().getStatus().equals("ok")) {
                                            pingEntityList.clear();
                                            socketPingDatabase.socketPingDao().deleteAll();
                                        }
                                    }
                            }

                            @Override
                            public void onFailure(Call<SocketPingResponse> call, Throwable t) {
                                Log.e("socketLogResponse", "Err : " + t.toString());
                            }
                        });

ApiClient类:

public class ApiClient {
    private static final String BASE_URL = Constants.SERVER;
    private static Retrofit retrofit = null;
    private static Context context;

    public static Retrofit getClient() {

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient.Builder client = new OkHttpClient.Builder();
        client.interceptors().add(interceptor);
        client.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request().newBuilder().addHeader("X-Client-Version", Constants.getAppVersionName()).build();
                return chain.proceed(request);
            }
        });
        client.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request().newBuilder().addHeader("uuid", Constants.getUUID(Constants.currentActivity)).build();
                return chain.proceed(request);
            }
        });

        client.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request().newBuilder().addHeader("agent", Constants.getAgent()).build();
                return chain.proceed(request);
            }
        });

        OkHttpClient client2 = client
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();

        Gson gson = new GsonBuilder()
                .setLenient()
                .create();

        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .client(client2)
                    .build();
        }
        return retrofit;
    }
}

如何解决此问题?

3 个答案:

答案 0 :(得分:0)

我认为当没有数据返回时,问题返回字符串。后端通常会发生此类错误。这个错误以前发生在我身上。您应该在没有可用数据时检查响应json

答案 1 :(得分:0)

Retrofit是类型安全的库。这意味着它仅等待特定(预定义)类型的对象。如果服务器发送了其他内容-它崩溃并显示错误。这是你的情况。只需检查原始服务器响应,您就会发现问题所在。

答案 2 :(得分:0)

尝试更改您的API调用

来自

@POST("api/log")
Call<SocketPingResponse> getSocketPingLog(@Header("jwt") String jwt, @Body SocketPingBodySendData socketPingBodySendData);

@POST("api/log")
Call<String> getSocketPingLog(@Header("jwt") String jwt, @Body SocketPingBodySendData socketPingBodySendData);


pingEntityList.addAll(socketPingDatabase.socketPingDao().getSocketPingEntityList());
                        SocketPingBodySendData pingBodySendData = new SocketPingBodySendData();
                        pingBodySendData.setAuction_id(auctionID);
                        pingBodySendData.setData(pingEntityList);
                        Toast.makeText(context, ""+pingEntityList.size(), Toast.LENGTH_SHORT).show();
                        Call<String> pingResponseCall = apis.getSocketPingLog(jwtToken, pingBodySendData);
                        pingResponseCall.enqueue(new Callback<String>() {
                            @Override
                            public void onResponse(Call<String> call, Response<String> response) {
                                    if (response.body() != null) {
                                        //Convert here your string response to Other POJO format
                                    }
                            }

                            @Override
                            public void onFailure(Call<String> call, Throwable t) {
                                Log.e("socketLogResponse", "Err : " + t.toString());
                            }
                        });