简体   繁体   English

如何用 jackson 序列化这个 json?

[英]how to serialize this json with jackson?

I have incoming json which looks like this:我收到的 json 看起来像这样:

{
  "ref": {
    "id": "1011"
  },
  "compset": [
      {
        "id": "23412"
      },
      {
        "id": "27964"
      },
      {
        "id": "51193"
      },
      {
        "id": "74343"
      },
      {
        "id": "537157"
      },
      {
        "id": "542023"
      },
      {
        "id": "601732"
      },
      {
        "id": "793808"
      },
      {
        "id": "891169"
      },
      {
        "id": "1246443"
      }
 ],
   "isCompliant": false,
    "updateTimestamp": null,
    "remainingMilliseconds": 0,
    "totalLockoutDays": 15
}

I have three classes that handle this response:我有三个类来处理这个响应:

for "id" field:对于“id”字段:

public class Competitor {
  @JsonProperty("id")
  @JsonFormat(shape = JsonFormat.Shape.NUMBER_INT)
  private Integer id; // this should be integer, can't change the type
}

for "compset" field:对于“compset”字段:

public class PropertyCompetitorsModel {
  private List<Competitor> competitors;
}

for response itself:对于响应本身:

public class CompSetResponse {
  @JsonProperty("compset")
  private PropertyCompetitorsModel compset;
}

As you can see I need only compset field.如您所见,我只需要 compset 字段。

With code above I am having this error:使用上面的代码,我遇到了这个错误:

Cannot deserialize instance of PropertyCompetitorsModel out of START_ARRAY token

Jackson library is used使用 Jackson 库

Use the following instead:请改用以下内容:

public class CompSetResponse {
  @JsonProperty("compset")
  private List<Competitor> compset;
}

Your current code is expecting a JSON as follows:您当前的代码需要 JSON 如下:

{
  "ref": {
    "id": "1011"
  },
  "compset": {
    "competitors": [
        {
          "id": "23412"
        },
        {
          "id": "27964"
        },
        {
          "id": "51193"
        },
        {
          "id": "74343"
        },
        {
          "id": "537157"
        },
        {
          "id": "542023"
        },
        {
          "id": "601732"
        },
        {
          "id": "793808"
        },
        {
          "id": "891169"
        },
        {
          "id": "1246443"
        }
    ],
  },
   "isCompliant": false,
    "updateTimestamp": null,
    "remainingMilliseconds": 0,
    "totalLockoutDays": 15
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM