尝试使用jackson注释类来表示json字符串

时间:2016-10-16 21:01:19

标签: java json jackson

我有一个来自外部源的JSON结构,并且在尝试构建可用于反序列化的类结构时遇到一些困难。我已经注册了json数组的每个成员都有一个数组项的名称(oneDevice) - 我第一次看到这个

{
  "pushResponse" : [
    {
      "oneDevice" : {
        "status" : "Error 0",
        "token" : "7676jbhjh",
        "type" : "gcm"
      }
    },
    {
      "oneDevice" : {
        "status" : "Error 0",
        "token" : "asdasf66a",
        "type" : "gcm"
      }
    }
]}

我尝试创建以下类结构,但在运行代码时收到错误消息:

@JsonIgnoreProperties( ignoreUnknown = true )
public class PushOkResponse {

  @JsonProperty("pushResponse")
  @XmlElement(required = true)
  protected PushResponseType pushResponse;
}


@JsonIgnoreProperties( ignoreUnknown = false )
public class PushResponseType {

  @JsonProperty( "oneDevice" )
  protected List<OneDeviceType> oneDevice;
}


@JsonIgnoreProperties( ignoreUnknown = false )
public class OneDeviceType {

  @XmlElement( required = true )
  @JsonProperty( "status" )
  protected String status;

  @XmlElement( required = true )
  @JsonProperty( "token" )
  private String token;

  @XmlElement( required = true )
  @JsonProperty( "type" )
  private String type;
}


PushOkResponse pushOkResponse = mapper.readValue(jsonInString, PushOkResponse.class);

以com.fasterxml.jackson.databind.JsonMappingException失败:无法反序列化(packageName ommitted)的实例... PushResponseType超出START_ARRAY令牌  at [来源:{“pushResponse”:[{“oneDevice”:{“status”:“Error 0”,“token”:“7676jbhjh”,“type”:“gcm”}}]}; line:1,column:22](通过引用链:( packageName ommitted)... PushOkResponse [“pushResponse”])

1 个答案:

答案 0 :(得分:0)

阅读以下帖子Related question我终于在发布问题后的短时间内开始工作。

如果我在PushOkResponse类中使用List,并在PushResponseType类中删除OneDeviceType的List,一切正常。像这样:

@JsonIgnoreProperties( ignoreUnknown = true )
public class StrettoOkResponse extends StrettoResponse {

  @JsonProperty("pushResponse")
  @XmlElement(required = true)
  protected List<PushResponseType> pushResponse;
}

@JsonIgnoreProperties( ignoreUnknown = false )
public class PushResponseType {

  @JsonProperty( "oneDevice" )
  protected OneDeviceType oneDevice;
}