POST时,Spring REST无法反序列化嵌套对象

时间:2017-07-14 01:31:02

标签: java spring jackson

尝试使用Spring启动应用程序进行POST时,我收到嵌套对象为空的错误。以下是代码......任何想法?

POST请求:

  {
      "id": 1,
      "username": "luisau",
      "password": "fe4354",
      "firstName": "Luisa",
      "lastName": "k",
      "dob": "2011-07-15",
      "streetName": "str",
      "streetNumber": "38",
      "city": "town",
      "postalCode": "43546",
      "country": "Germany",
      "registrationTime": "2017-07-13T16:45:34Z",
      "registrationIp": "192.23.45.6",
      "gender": "Female",
      "registrationChannel": {"id": 2}
    }

类别:

@Entity
public class Customer {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    private RegistrationChannel registrationChannel;

    private String email;

    private String username;

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private String password;

    @Enumerated(EnumType.STRING)
    private Gender gender;

    private char title;

    private String firstName;

    private String lastName;

    @Convert(converter = Jsr310JpaConverters.LocalDateConverter.class)
    private LocalDate dob;

    @Embedded
    @JsonUnwrapped
    private Address address;

    private String registrationIp;

    private Instant registrationTime;

    //getters, setters omitted

Caused by: org.mariadb.jdbc.internal.util.dao.QueryException: Column 'registration_channel_id' cannot be null
Query is: insert into customer (city, country, postal_code, street_name, street_number, dob, email, first_name, gender, last_name, password, registration_channel_id, registration_ip, registration_time, title, username) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?), parameters

2 个答案:

答案 0 :(得分:0)

错误消息已清除,您的registrationChannel为空。原因是您不能只发送registrationChannel ID,您需要在ORM中存储registrationChannel对象。

例如在您的save数据库方法中:

public void save(Customer customer, int registrationChannelId) {
    RegistrationChannel registrationChannel = findRegistrationChannel(registrationChannelId);

   customer.addRegistrationChannel(registrationChannel);

   // save your customer
}

答案 1 :(得分:0)

我这样解决了:

我必须调整POST的有效负载以包含嵌套资源的URL

{
      "id": 1,
      "username": "luisau",
      "password": "fe4354",
      "firstName": "Luisa",
      "lastName": "k",
      "dob": "2011-07-15",
      "streetName": "str",
      "streetNumber": "38",
      "city": "town",
      "postalCode": "43546",
      "country": "Germany",
      "registrationTime": "2017-07-13T16:45:34Z",
      "registrationIp": "192.23.45.6",
      "gender": "Female",
      "registrationChannel": "/registrationChannels/2"
    }