JsonMappingException:无法从 START_OBJECT 令牌中反序列化枚举实例

May*_*urb 5 enums spring-mvc set jackson

我的 Json 如下所示

{
name: "math",
code:null,
description:"Mathematics",
id:null,
name:"math",
noExam:null,
teacher:{
	id: "57869ced78aa7da0d2ed2d92", 
	courseGroup:"LKG",
	experties:[{type: "SOCIALSTUDIES", id: "3"}, {type: "PHYSICS", id: "4"}]

	},
id:"57869ced78aa7da0d2ed2d92"
}
Run Code Online (Sandbox Code Playgroud)

如果你看到我的实体类,我在 Teacher.java 中有一组枚举

当我尝试发布此内容时出现错误

JsonMappingException: Can not deserialize instance of com.iris.fruits.domain.enumeration.Experties out of START_OBJECT token
Run Code Online (Sandbox Code Playgroud)

我已经尝试了几乎所有的解决方案,例如DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY,但没有成功。

JsonMappingException: Can not deserialize instance of com.iris.fruits.domain.enumeration.Experties out of START_OBJECT token
Run Code Online (Sandbox Code Playgroud)

小智 0

您的类应该与 json 的结构匹配。并且在您的输入 json 中不应重复键。

我猜你的课应该像下面这样:

public class Subject implements Serializable {
// all the other fields 
    String name;
    String code;
    String description;
    String id;
    String noExam;
    @JoinColumn(name = "teacher_id")
    private Teacher teacher;

  // getter and setter
  }



public class Teacher implements Serializable {
// all the other fields 

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private String id;

    @Enumerated(EnumType.STRING)
    @Column(name = "experties")
    @JsonProperty("experties")
    private List< Experties> experties;

    String courseGroup;
  // getter and setter
  }



 @JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum Experties implements Serializable {
    MATH(1,"MATH"),
    SCIENCE(2,"SCIENCE"),
    SOCIALSTUDIES(3,"SOCIALSTUDIES"),
    PHYSICS(4,"PHYSICS"), 
    CHEMISTRY(5,"CHEMISTRY");

    @JsonSerialize(using = ToStringSerializer.class) 
    private String type;

    @JsonSerialize(using = ToStringSerializer.class) 
    private Integer id;

    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }


    Experties(Integer id, final String type) {
        this.id = id;       
        this.type = type; 
    }


}
Run Code Online (Sandbox Code Playgroud)