Jackson 2.11.4:为缺失的 JSON 字段设置默认值

Ran*_*aul 5 java jackson java-8 spring-boot

我有下面的 JSON

"Choices": [
        {
        "choiceId": "1"
        
    },
    {
        "choiceId": "2",
        "choiceType": null
    }
    ]
Run Code Online (Sandbox Code Playgroud)

下面是 POJO,我需要两个构造函数,因为如果 json 中没有,choiceType我需要将其默认为Yes,如果 choiceTypejson 中存在null值,那么它不应该默认为Yes

@Getter
@ToString
@Setter
@NoArgsConstructor
public class Choices {
    @JsonProperty("choiceId")
    @NonNull
    private String choiceId;

    @JsonProperty("choiceType")
    private String choiceType;

    @JsonCreator
    @JsonIgnoreProperties(ignoreUnknown = true)
    public Choices(@JsonProperty("choiceId") String choiceId) {
        this.choiceType = choiceType !=null ? choiceType : "Yes";
        this.choiceId = choiceId;
    }

    public Choices(@JsonProperty("choiceId") String choiceId, @JsonProperty("choiceType") String choiceType) {
        this.choiceType = choiceType;
        this.choiceId = choiceId;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的目标是当上面的 Json 被反序列化并且我有下面的测试用例时有一个选择列表

@Test
    public void testChoices(){
        ObjectMapper objectMapper = new ObjectMapper();
        String json = "[ { \"choiceId\": \"1\" }, { \"choiceId\": \"2\", \"choiceType\": null } ]";
        
        List<Choices> choices = objectMapper.convertValue(json, new TypeReference<List<Choices>>() {
        });
        assertTrue(choices.get(0).getChoiceId().equals("1"));
        assertTrue(choices.get(0).getChoiceType().equals("Yes"));
        assertTrue(choices.get(1).getChoiceType().equals("2"));
        assertNull(choices.get(1).getChoiceType());
    }
Run Code Online (Sandbox Code Playgroud)

当我尝试反序列化下面的 json. 我尝试了很多解决方案,但仍然没有成功,有人可以帮助我解决这个问题吗?

Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Invalid definition for property `choiceType` (of type `com.onetrust.ds.request.dto.rest.Choices`): Could not find creator property with name 'choiceType' (known Creator properties: [choiceId])
 at [Source: UNKNOWN; line: -1, column: -1]
Run Code Online (Sandbox Code Playgroud)

use*_*814 6

您可以删除 args 构造函数并将默认值设置为“Yes”。如果 value 显式设置为 null 或某个值,则会对其进行赋值。如果缺少值,它将被默认。

@Getter
@ToString
@Setter
@NoArgsConstructor
public class Choices {
    @JsonProperty("choiceId")
    @NonNull
    private String choiceId;

    @JsonProperty("choiceType")
    private String choiceType = "Yes";

}
Run Code Online (Sandbox Code Playgroud)

参考 -杰克逊:如果财产丢失怎么办?