Spring @RequestBody 继承

wes*_*eyy 7 java inheritance spring json jackson

我已经阅读了几篇试图解释这一点的帖子,但我无法让它发挥作用。我有一个场景,其中JSON我的服务的输入可以是多个子类型。基本上,我有一个基类UserDto,然后ClientDtoOwnerDto这两者的延伸从UserDto.我想实现,该控制器能够解决的具体亚型UserDto到正确的类的对象。所以像这样的事情。

@ResponseStatus(HttpStatus.OK)
    @RequestMapping(value = "/", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public void doSomething(@RequestBody UserDto user) {
        ClientDto client = (ClientDto) user;
        // do something
    }
Run Code Online (Sandbox Code Playgroud)

我试过这样的事情。基本上我想通过profileTypeenum 类型的字段来确定具体对象的类型ProfileType,值OWNERCLIENT

UserDto.java

@JsonTypeInfo(use = Id.CLASS, include = As.PROPERTY, property = "profileType", visible = true)
@JsonSubTypes({
    @JsonSubTypes.Type(value = ClientDto.class, name = "Client"),
    @JsonSubTypes.Type(value = OwnerDto.class, name = "Owner")
})
public class UserDTO {

    @NotNull
    @Size(min = 0, max = 256)
    private ProfileType profileType;

    @NotNull
    @Size(min = 0, max = 512)
    private String email;

    // ...
}
Run Code Online (Sandbox Code Playgroud)

ClientDto.java

public class ClientDto extends UserDto {

    private Integer salary;

    private Integer efficiency;

    // ... 
}
Run Code Online (Sandbox Code Playgroud)

我尝试将以下 JSON 发布到此端点。

{
        "email": "eddie.barra22@gmail.com",
        "profileType": "CLIENT",
        "salary": "100",
        "efficiency": "99"
    }
Run Code Online (Sandbox Code Playgroud)

我希望这可以解决为一种ClientDto. 相反,我只收到了400 Bad Request错误。

问题是:

  1. 我如何解决这个问题,并使@RequestBody继承工作?
  2. 有没有办法在子类型上指定注释而不是在超类型上定义所有注释?

pvp*_*ran 9

您的代码中有几个错误。

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "profileType", visible = true)
@JsonSubTypes({
    @JsonSubTypes.Type(value = ClientDto.class, name = "CLIENT"),
    @JsonSubTypes.Type(value = OwnerDto.class, name = "OWNER")
})
public class UserDTO {
 .....
}
Run Code Online (Sandbox Code Playgroud)
  1. 您说 ProfileType 枚举有OWNERCLIENT。但您已指定JsonSubTypes.Type为客户和所有者。因此不匹配
  2. 改成JsonTypeInfo.Id.CLASSJsonTypeInfo.Id.NAME