当对象不为null时无法解析

时间:2019-06-13 21:01:26

标签: java gson

当我尝试使用gson不为null的对象解析时,首先,我在尝试解析时为对象的每个字段注入了一个字符串常量,代码未显示错误,并且它不会继续

这是代码的不同之处:

我的对象是在另一个这样的类中声明的CurrentErrorList(可以为null或为空):

@JsonAdapter(EmptyStringAsEmptyErrorTypeAdapter.class)
@SerializedName("CurrentErrorList")
CurrentErrorList currentErrorList;

对象声明:

public class CurrentErrorList {

@SerializedName(value = "Error")
private Error error;
...
}

错误类声明:

public class Error {

@SerializedName(value = "ErrorHexCode")
private String errorHexCode;

@SerializedName(value = "ErrorName")
private String errorName;

@SerializedName(value = "ErrorDescription")
private String errorDescription;
}

,EmptyStringAsEmptyErrorTypeAdapter是:

public class EmptyStringAsEmptyErrorTypeAdapter extends TypeAdapter<CurrentErrorList> {

      @Override
      public void write(JsonWriter out, CurrentErrorList value) throws IOException {
        out.beginObject();
        out.name("CurrentErrorList");
        out.value(value.getError().getErrorName());
        out.value(value.getError().getErrorHexCode());
        out.value(value.getError().getErrorDescription());
        out.endObject();
      }

      @Override
      public CurrentErrorList read(JsonReader in) throws IOException {
          CurrentErrorList result = new CurrentErrorList();
        result.setError(new Error());
        result.getError().setErrorName("");

        if (in.peek() == JsonToken.BEGIN_OBJECT) {

            result.getError().setErrorName("ErrorName");
            result.getError().setErrorName("ErrorDescription");
            result.getError().setErrorName("ErrorHexCode");

        } else {
            in.nextString();
            return null;
        }
        return result;
      }

}

0 个答案:

没有答案