预期为STRING,但为BEGIN_OBJECT

时间:2019-04-17 15:51:17

标签: java json parsing gson

我已经阅读了很多有关此错误的答案,但找不到适合我的解决方案,也许类对象并不相同

我的错误是:

com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:预期为STRING,但为BEGIN_OBJECT

所以,我只是想像这样从JSON获取对象:

JsonObject mS1SystemStatusJsonObject = parameterEntries.getValue().getAsJsonObject();

MS1SystemStatusResponse mS1SystemStatusResponse = gson.fromJson(mS1SystemStatusJsonObject, MS1SystemStatusResponse.class);

我的JsonObject是:

{
 "WARNING_CONDITION_LIST":
  {
   "warningConditionList": {"warningCondition":"BLACK_POSTAL_INK_WF_COND"}
   },
 "DISABLING_CONDITION_LIST": {"disablingConditionList":""},
 "CurrentErrorList":"",
 "LockState":"lockspend",
"SystemReadyState":true
}

我的与众不同的POJO(我不把get和set简称为代码):

public class MS1SystemStatusResponse{

@SerializedName("LockState")
String lockState;

@SerializedName("SystemReadyState")
Boolean systemReadyState;

@SerializedName("WARNING_CONDITION_LIST")
WARNING_CONDITION_LIST warningConditionListMy;

@SerializedName("DISABLING_CONDITION_LIST")
DISABLING_CONDITION_LIST disablingConditionListMy;

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


public class WARNING_CONDITION_LIST {

@SerializedName(value = "warningConditionList")
@JsonAdapter(EmptyStringAsNullTypeAdapter.class)
WarningConditionList warningConditionList;


public class DISABLING_CONDITION_LIST {

@SerializedName(value = "disablingConditionList")
@JsonAdapter(EmptyStringAsNullTypeAdapter.class)
DisablingConditionList disablingConditionList;

public class CurrentErrorList {

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


public class WARNING_CONDITION_LIST {

@SerializedName(value = "warningConditionList")
@JsonAdapter(EmptyStringAsNullTypeAdapter.class)
WarningConditionList warningConditionList;


public class WarningConditionList {

@SerializedName(value = "warningCondition")
String warningCondition;

这是完整的堆栈跟踪以及我之前忘记添加的另一个类:

Stacktrace:

java.lang.IllegalStateException: Expected STRING but was BEGIN_OBJECT
    com.google.gson.internal.bind.JsonTreeReader.nextString(JsonTreeReader.java:154)
    com.pb.marqueo.connect.plus.api.common.model.response.EmptyStringAsNullTypeAdapter.read(EmptyStringAsNullTypeAdapter.java:24)
    com.pb.marqueo.connect.plus.api.common.model.response.EmptyStringAsNullTypeAdapter.read(EmptyStringAsNullTypeAdapter.java:10)
    com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:117)
    com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:217)
    com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:117)
    com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:217)
    com.google.gson.Gson.fromJson(Gson.java:861)
    com.google.gson.Gson.fromJson(Gson.java:926)
    com.google.gson.Gson.fromJson(Gson.java:899)
    com.pb.marqueo.connect.plus.api.core.service.impl.ConnectPlusServicesImpl.getMS1SystemStatus(ConnectPlusServicesImpl.java:410)
    com.pb.marqueo.connect.plus.api.core.facade.impl.ConnectPlusBusinessServicesImpl.startProduction(ConnectPlusBusinessServicesImpl.java:1236)
    com.pb.marqueo.connect.plus.rest.services.impl.ConnectPlusControllerImpl.startProd(ConnectPlusControllerImpl.java:280)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:498)
    org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    com.pb.marqueo.common.filter.OriginFilter.doFilter(OriginFilter.java:70)

类适配器:

public class EmptyStringAsNullTypeAdapter extends TypeAdapter<String> {

    @Override
    public void write(JsonWriter out, String value) throws IOException {
        out.value(value);
    }

    @Override
    public String read(JsonReader in) throws IOException {
        if (in.peek() == JsonToken.NULL) {
            in.nextNull();
            return null;
        }

        String result = in.nextString();
        if ("".equals(result)) {
            return null;
        }
        return result;
    }
}

我从1周开始转身:(

1 个答案:

答案 0 :(得分:1)

好的,所以从评论中的对话中我了解到您希望能够对这两种情况进行反序列化:

{
  "WARNING_CONDITION_LIST": {
      "warningConditionList": {"warningCondition":"BLACK_POSTAL_INK_WF_COND"}
  },
  ...
}

{
  "WARNING_CONDITION_LIST": ""
  ...
}

在第一种情况下,您需要对象,在第二种情况下,您需要null

我注意到的第一件事是您在错误的位置添加了@JsonAdapter注释。它实际上应该在WARNING_CONDITION_LIST字段中。像这样:

public class MS1SystemStatusResponse {
  // ...
  @SerializedName("WARNING_CONDITION_LIST")
  @JsonAdapter(EmptyStringAsNullTypeAdapter.class)
  WARNING_CONDITION_LIST warningConditionListMy;
  // ...
}

但是,仅此一项并不能解决您的问题。问题出在EmptyStringAsNullTypeAdapter之内。它期望该字段只是一个字符串,并且在可以作为对象时不处理这种情况。为此,我们可以编写以下适配器:

public class EmptyStringAsEmptyWarningConditionlTypeAdapter extends TypeAdapter<WARNING_CONDITION_LIST> {

  @Override
  public void write(JsonWriter out, WARNING_CONDITION_LIST value) throws IOException {
    out.beginObject();
    out.name("warningConditionList");
    out.value(value.warningConditionList.warningCondition);
    out.endObject();
  }

  @Override
  public WARNING_CONDITION_LIST read(JsonReader in) throws IOException {
    WARNING_CONDITION_LIST result = new WARNING_CONDITION_LIST();
    result.warningConditionList =  new WarningConditionList();
    result.warningConditionList.warningCondition = "";

    if (in.peek() == JsonToken.BEGIN_OBJECT) {
        in.beginObject();
        in.nextName();
        in.beginObject();
        in.nextName();
        result.warningConditionList.warningCondition = in.nextString();
        in.endObject();
        in.endObject();
    } else {
        in.nextString();
        return null;
    }
    return result;
  }
}

基本上,它将检查您是否有字符串或对象,并分别返回null或对象。

这仅适用于我向您展示了json的这2种情况,应该足以帮助您弄清其余的情况。

CurrentErrorList可能会遇到类似的问题。