Java:我的JSON没有被正确地反序列化成它的等价Java类?

kpbwa7wx  于 2023-01-19  发布在  Java
关注(0)|答案(1)|浏览(75)

我有下面的json,我想把它反序列化成一个类。我没有用来组成json的java类。所以我试着自己写类。
但是,反序列化时存在一个问题。
body is always null
所有的Maven们,你们能帮我找出我做错了什么吗?
我将非常感谢你的帮助

JSON Input:
{
    "totalSize": 2,
    "done": true,
    "records": [
      {
        "attributes": {
          "type": "record",
          "url": "a string"
        },
        "Body": "a string + something additional"
      },
      {
        "attributes": {
          "type": "record",
          "url": "b string"
        },
        "Body": "b string + something additional"
      }
    ]
  }
Code that does the deserialization:
final Response response = new ObjectMapper().readValue(json, Response.class);
Java Classes Input:

    @Getter
    @Setter
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
    public static class Attributes {
        @NotBlank
        private String type;

        @NotBlank
        private String url;
    }

    @Getter
    @Setter
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
    public static class Record {
        private Attributes attributes;

        @NotBlank
        public String body;
    }

    @Getter
    @Setter
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
    public static class Response {
        private int totalSize;

        private boolean done;

        private List<Record> records;
    }
wwwo4jvm

wwwo4jvm1#

我没有看到属性名称是Body而不是body
因此,我需要使用下面的注解来使它工作:

@JsonProperty("Body")

i.e., 

    @Getter
    @Setter
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
    public static class Record {
        private Attributes attributes;

        @NotBlank
        @JsonProperty("Body")
        public String body;
    }

相关问题