gpt4 book ai didi

java - Jackson - @JsonTypeInfo 属性被映射为空?

转载 作者:IT老高 更新时间:2023-10-28 20:46:26 36 4
gpt4 key购买 nike

我有这样的回应:

{  
"id":"decaa828741611e58bcffeff819cdc9f",
"statement":"question statement",
"exercise_type":"QUESTION"
}

然后,基于 exercise_type 属性,我想实例化不同的对象实例(ExerciseResponseDTO 的子类),所以我创建了这个混合:

@JsonTypeInfo(  
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "exercise_type")
@JsonSubTypes({
@Type(value = ExerciseChoiceResponseDTO.class, name = "CHOICE"),
@Type(value = ExerciseQuestionResponseDTO.class, name = "QUESTION")})
public abstract class ExerciseMixIn
{}

public abstract class ExerciseResponseDTO {

private String id;
private String statement;
@JsonProperty(value = "exercise_type") private String exerciseType;

// Getters and setters
}

public class ExerciseQuestionResponseDTO
extends ExerciseResponseDTO {}

public class ExerciseChoiceResponseDTO
extends ExerciseResponseDTO {}

所以我创建我的 ObjectMapper 如下

ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(ExerciseResponseDTO.class, ExerciseMixIn.class);

我的测试:

ExerciseResponseDTO exercise = mapper.readValue(serviceResponse, ExerciseResponseDTO.class)
Assert.assertTrue(exercise.getClass() == ExerciseQuestionResponseDTO.class); // OK
Assert.assertEquals("decaa828741611e58bcffeff819cdc9f" exercise.getId()); // OK
Assert.assertEquals("question statement", exercise.getStatement()); // OK
Assert.assertEquals("QUESTION", exercise.getExerciseType()); // FAIL. Expected: "QUESTION", actual: null

问题在于,由于某种原因,被用作 @JsonTypeInfo 上的属性的 exercise_type 属性被映射为 null。知道如何解决这个问题吗?

最佳答案

最后,我在 API Doc 中找到了解决方案

Note on visibility of type identifier: by default, deserialization (use during reading of JSON) of type identifier is completely handled by Jackson, and is not passed to deserializers. However, if so desired, it is possible to define property visible = true in which case property will be passed as-is to deserializers (and set via setter or field) on deserialization.

所以解决方案只是简单地添加 'visible' 属性,如下所示

@JsonTypeInfo(  
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "exercise_type",
visible = true)
@JsonSubTypes({
@Type(value = ExerciseChoiceResponseDTO.class, name = "CHOICE"),
@Type(value = ExerciseQuestionResponseDTO.class, name = "QUESTION")})
public abstract class ExerciseMixIn
{}

希望这对其他人有所帮助。

关于java - Jackson - @JsonTypeInfo 属性被映射为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33611199/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com