【问题标题】:Optional nested JSON object with Spring RestTemplate带有 Spring RestTemplate 的可选嵌套 JSON 对象
【发布时间】:2020-03-28 16:08:46
【问题描述】:

在我尝试与 Spring RestTemplate 一起使用的 API 中,我收到了一个可选字段,如下例所示。 这个可选字段是一个嵌套对象,我想使用一个嵌套类来映射它。

{
  "name": "John",
  "age": 30
}
{
  "name": "John",
  "age": 30,
  "car": {
    "year": 1984,
    "color": "red"
  }
}

我目前的班级定义:

public class User {
    public class Car {
        @Getter
        @Setter
        public String color;

        @Getter
        @Setter
        public Integer year;
    }

    @Getter
    @Setter
    public String name;

    @Getter
    @Setter
    public Integer age;

    @Getter
    @Setter
    public Car car;
}

通过调用:

ResponseEntity<User> response = restTemplate.exchange("http://....", HttpMethod.POST, request, User.class);

我得到以下异常:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of '....User$Car' (although at least one Creator exists): can only instantiate non-static inner class by using default, no-argument constructor

如果节点存在于 json 中,我如何拥有 null 或使用 Car 类实例化的 car 属性?

【问题讨论】:

    标签: json spring resttemplate


    【解决方案1】:

    您可以尝试以下更新的课程。变化是将内部类定义为静态的。

    public  class User {
        public static class Car {
            @Getter
            @Setter
            public String color;
    
            @Getter
            @Setter
            public Integer year;
        }
    
        @Getter
        @Setter
        public String name;
    
        @Getter
        @Setter
        public Integer age;
    
        @Getter
        @Setter
        public Car car;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-07
      • 2019-03-15
      • 2016-11-09
      • 2020-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多