我正在学习 Spring Boot,但是我停止了这个问题。我有一个带有 @JsonSubTypes 的人抽象类,一个使用 @JsonTypeName 扩展 Person 的 Client 和 Seller 类。所有请求都会返回错误:尝试解析子类型时缺少类型 id。
人员类别
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = As.PROPERTY, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = Client.class, name = "client"),
@JsonSubTypes.Type(value = Seller.class, name = "seller")
// @JsonSubTypes.Type(value = Provider.class, name = "provider"),
})
public abstract class Person implements Comparable<Person>{
@Id
@Field("_id")
@JsonIgnore
private String code;
private String name;
private String phone;
private String email;
@Field("created_at")
private DateTime registerDate;
public Person(String name, String phone, String email) {
this.name = name;
this.phone = phone;
this.email = email;
}
客户端类
@Document("clients")
@JsonTypeName("client")
public class Client extends Person{
@Indexed(unique=true)
private String cpf;
@Field("credit_limit")
private Double creditLimit;
public Client(String name, String phone, String email, String cpf,
Double creditLimit) {
super(name, phone, email);
this.cpf = cpf;
this.creditLimit = creditLimit;
}
卖家类别
@Document("sellers")
@JsonTypeName("seller")
public class Seller extends Person {
@Indexed(unique=true)
private String cpf;
@Field("monthly_goal")
private Double monthlyGoal;
public Seller(String name, String phone, String email, String cpf,
Double monthlyGoal) {
super(name, phone, email);
this.cpf = cpf;
this.monthlyGoal = monthlyGoal;
}
初始方法
@PostMapping("sale/store")
@ResponseBody
public ResponseEntity<String> store(@RequestBody Client client) {
return ResponseEntity.ok("ok");
}
最佳答案
您似乎缺少提交"type":"client"
JSON 请求正文中的字段。
但您还需要在 Person
中提供默认构造函数。 , Client
, Seller
类或用 @JsonCreator
标记可用的构造函数注释:
// Client with explicit creator
@JsonCreator
public Client(
@JsonProperty("name") String name,
@JsonProperty("phone") String phone,
@JsonProperty("email") String email,
@JsonProperty("cpf") String cpf,
@JsonProperty("creditLimit") Double creditLimit) {
super(name, phone, email);
this.cpf = cpf;
this.creditLimit = creditLimit;
}
// ------
// seller: use default constructor (also to be added in `Person`) for Jackson
public Seller() {}
// person
public Person() {}
关于java - @JsonTypeName 不起作用并在尝试解析子类型时返回 Missing type id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61993488/