当前位置: 首页 > 知识库问答 >
问题:

JsonMappingException:无法反序列化START_OBJECT令牌外的枚举实例

慕容聪
2023-03-14
{
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"
}

如果您看到我的实体类,我在teacher.java中有一组枚举。

当我试着发布这个时,我会出错

JsonMappingException: Can not deserialize instance of com.iris.fruits.domain.enumeration.Experties out of START_OBJECT token

我已经尝试了几乎所有的解决方案,比如deserializationfeature.accept_single_value_as_array,但没有成功。

public class Subject implements Serializable {
// all the other fields 
    @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;

  // 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; 
	}
	
	
}

共有1个答案

危飞文
2023-03-14

出现此问题是因为枚举中有一个自定义序列化器(@jsonFormat(shape=jsonFormat.shape.object))。因此,为了解决这个问题,您需要一个自定义的反序列化程序。

可以使用以下方法定义自定义反序列化程序:

@JsonFormat(shape = JsonFormat.Shape.OBJECT) // custom serializer
@JsonDeserialize(using = MyEnumDeserializer.class) // custom deserializer
public enum Experties implements Serializable {
    ...
}

自定义反序列化程序为:

public static class MyEnumDeserializer extends JsonDeserializer<Experties> {
    @Override
    public Experties deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        JsonNode node = jsonParser.getCodec().readTree(jsonParser);
        String type = node.get("type").asText();
        return Stream.of(Experties.values())
           .filter(enumValue -> enumValue.getType().equals(type))
           .findFirst()
           .orElseThrow(() -> new IllegalArgumentException("type "+type+" is not recognized"));
    }
}
 类似资料: