我正在尝试将 null 值设置为 JSON 有效负载中的空值数据库。这个问题是因为我对
social
实体字段有独特的约束而引起的。
我有一个请求 DTO,如下所示:
@Value
@With
@Builder
@Jacksonized
public class AccountCreateRequest {
@NotBlank
String firstName;
String phone;
@Password
@NotBlank
String password;
@Email(message = "Email is not valid.")
@NotBlank
String email;
@NotBlank
String role;
SocialDto social;
}
嵌套社交 DTO 看起来像
@Value
@Builder
@Jacksonized
public class SocialDto {
@JsonInclude(JsonInclude.Include.NON_EMPTY)
String telegramId;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
String linkedinLink;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
String githubLink;
}
Json 示例:
{
...fields...,
social: {
telegramId: "",
githubLink: "",
...
}
}
此 JSON 对象使用社交空字符串进行反序列化,并且不会忽略该值。 将注释移至类级别 - 对我没有帮助。
我该如何解决这个问题?
@JsonInclude(JsonInclude.Include.NON_EMPTY)
无法达到在对象反序列化时将空字符串视为 null 的预期目的。此注释用于在对象到 JSON 序列化中包含字段。
您需要添加一个自定义反序列化器,如下所示:如何将 java.lang.String 的空白 JSON 字符串值反序列化为 null?
为了将其与已在班级级别注册了
@Jacksonized
的 @JsonDeserialize(using = x.class)
相结合,您可以执行以下操作:
public class JsonStringDeserializer extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
JsonNode node = jsonParser.readValueAsTree();
String nodeText = node.asText();
// todo: isBlank or isEmpty depending on your needs
if (nodeText.isBlank()) {
return null;
}
return nodeText;
}
}
并使用以下代码解析 JSON 对象:
SimpleModule stringModule = new SimpleModule();
stringModule.addDeserializer(String.class, new JsonStringDeserializer());
ObjectMapper jsonObjectMapper = new ObjectMapper();
jsonObjectMapper.registerModule(stringModule);
jsonObjectMapper.readValue(input, modelClass);
或者,如果您不控制
@JsonDeserialize(using = JsonStringDeserializer.class)
,您可以在每个需要它的字符串字段上添加 ObjectMapper
。