java.io.EOFException:第1行的输入结束第1行路径$在Gson解析器中

时间:2017-04-18 09:34:27

标签: java android json gson

我正在使用Gson和Retrofit解析JSON字符串。我有这个JSON字符串:

{"message":["Email has already been taken"]}

我仍然得到以下异常,并且不知道原因:

java.io.EOFException: End of input at line 1 column 1 path $
    at com.google.gson.stream.JsonReader.nextNonWhitespace(JsonReader.java:1393)
    at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:549)
    at com.google.gson.stream.JsonReader.peek(JsonReader.java:425)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:205)
    at com.google.gson.TypeAdapter.fromJson(TypeAdapter.java:260)
    at com.google.gson.TypeAdapter.fromJson(TypeAdapter.java:273)

知道如何获得message字段价值的人请帮助我。

BaseApiDto.java

public class BaseApiDto {

    @SerializedName("message")
    public String[] message;

    public String getError() {
        return message[0];
    }

}

HandErrorUtils.java

public static void handleError(FragmentActivity activity, Throwable e) {
    String msg = null;
    if(e instanceof HttpException){
        // Error message in json
        Gson gson = new Gson();
        TypeAdapter<BaseApiDto> adapter = gson.getAdapter(BaseApiDto.class);
        ResponseBody body = ((HttpException) e).response().errorBody();

        // Status code
        HttpException httpException = (HttpException) e;
        int statusCode = httpException.code();

        if (statusCode == 500) {
            showErrorDialog(activity, activity.getString(R.string.dialog_msg_error_401), true);
        } else if (statusCode == 401) {
            showErrorDialog(activity, activity.getString(R.string.dialog_msg_error_401), true);
        } else {
            try {
                Timber.w("body.string() " + body.string());

                // TODO : EXCEPTION HAPPEN IN HERE
                BaseApiDto errorDto = adapter.fromJson(body.string());

                msg = errorDto.getError();

                Timber.w("msg " + msg);
            } catch (Exception ex) {
                // TODO : EXCEPTION HAPPEN IN HERE
                ex.printStackTrace();
            }

            showErrorDialog(activity, msg, false);
        }

    }
}

更新我将body.toString()分配给变量,不知何故有效。

String response = body.string();

BaseApiDto errorDto = adapter.fromJson(response);

1 个答案:

答案 0 :(得分:1)

之所以有效,是因为我没有两次致电body.string()

我将body.toString()分配给变量,以某种方式起作用。

String response = body.string();

BaseApiDto errorDto = adapter.fromJson(response);