JsonIgnoreProperties 不适用于 JsonCreator 构造函数

我有以下实体,我将其用作对控制器的请求之一的目标 POJO:


Entity

@Table(name="user_account_entity")

@JsonIgnoreProperties(ignoreUnknown = true)

@JsonSerialize(using = UserAccountSerializer.class)

public class UserAccountEntity implements UserDetails {

    //...

    private String username;


    private String password;


    @PrimaryKeyJoinColumn

    @OneToOne(mappedBy= "userAccount", cascade = CascadeType.ALL, fetch = FetchType.LAZY)

    private UserEntity user;


    @PrimaryKeyJoinColumn

    @OneToOne(mappedBy= "userAccount", cascade = CascadeType.ALL, fetch = FetchType.LAZY)

    private UserAccountActivationCodeEntity activationCode;


    @JsonCreator

    public UserAccountEntity(@JsonProperty(value="username", required=true) final String username, @JsonProperty(value="password", required=true) final String password) {

      //....

    }


    public UserAccountEntity() {}


    //.....

}

当我在请求中放入意外字段时,它抛出MismatchedInputException并失败并显示以下消息:


com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.myproject.project.core.entity.userAccountActivationCode.UserAccountActivationCodeEntity` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('9WL4J')

 at [Source: (PushbackInputStream); line: 4, column: 20] (through reference chain: com.myproject.project.core.entity.userAccount.UserAccountEntity["activationCode"])

在控制器中,我有:


@InitBinder

public void binder(WebDataBinder binder) {

    binder.addValidators(new CompoundValidator(new Validator[] {

            new UserAccountValidator(),

            new UserAccountActivationCodeDTOValidator() }));

}

我提出请求的端点是:


@Override

public UserAccountEntity login(@Valid @RequestBody UserAccountEntity account,

        HttpServletResponse response) throws MyBadCredentialsException, InactiveAccountException {

    return userAccountService.authenticateUserAndSetResponsenHeader(

            account.getUsername(), account.getPassword(), response);

}


慕哥9229398
浏览 126回答 1
1回答

慕侠2389804

触发错误是因为您在 json 中有:"activationCode" : "9WL4J"然而杰克逊不知道如何将字符串“9WL4J”映射到对象 UserAccountActivationCodeEntity我猜字符串“9WL4J”是 UserAccountActivationCodeEntity 的主键 id 的值,在这种情况下,您应该在 json 中有:"activationCode" : {"id" : "9WL4J"}如果不是这种情况,请使用自定义 Deseralizer 来告诉 Jackson 如何将字符串映射到对象。您可以在您的实体上使用 @JsonDeserialize。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java