【发布时间】:2021-09-02 16:43:57
【问题描述】:
我有以下 JSON
"Choices": [
{
"choiceId": "1"
},
{
"choiceId": "2",
"choiceType": null
}
]
下面是 POJO,我需要两个构造函数,因为如果 json 中没有 choiceType 我需要将其默认为 Yes,如果 json 中的 choiceType 存在 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;
}
}
我的目标是当上述 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());
}
当我尝试反序列化下面的 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]
【问题讨论】:
-
尝试不使用 Lombok。
-
@Nemanja 试过没有 Lombok 但没有运气
标签: java spring-boot java-8 jackson