为什么@jsoninclude(jsoninclude.include.non_empty)不起作用?
我正在尝试将零值设置为JSON有效载荷的空值数据库。这个问题引起了Beagause,我对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对象被社会空字符串进行了测试,并且不会忽略该值。 将注释转移到班级级别 - 对我无济于事。
我该如何解决此问题?
I am trying to set null values to database of empty values from JSON payload. This problem caused beacause I have unique constraints on social
entity fields.
I have request DTO that looks like:
@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;
}
Nested social DTO looks like
@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 example:
{
...fields...,
social: {
telegramId: "",
githubLink: "",
...
}
}
This JSON object is deserialized with social empty strings and doesn't ignore that values.
Moving annotation to the class level - didn't help for me.
How could I fix this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
@jsoninclude(jsoninclude.include.non_empty)
不适合将空字符串视为对象避免对象的预定目的。该注释是为了将字段包括在对象中,以json序列化。您需要添加这样的自定义求职者:如何将空白的JSON字符串值归为java.lang.string?
为了将其与
@jacksonized
结合起来,该 已经注册了> @jsondeserialize(使用= x.class)
在类级别上,您可以执行以下操作:并使用以下代码解析JSON对象:
或者您可以添加
@jsondeserialize(used = jsonstringDeserialializer.class.class))
在每个字符串字段上,如果您不控制ObjectMapper
,则需要它。@JsonInclude(JsonInclude.Include.NON_EMPTY)
does not work for the intended purpose of treating empty strings as null on object deserialization. This annotation is for including fields in Object to JSON serialization.You need to add a custom Deserializer like so: How to deserialize a blank JSON string value to null for java.lang.String?
In order to combine this with
@Jacksonized
, which already registers a@JsonDeserialize(using = x.class)
on the class level, you can do the following:and parse the JSON object with the following code:
Or you can add
@JsonDeserialize(using = JsonStringDeserializer.class)
on every String field that needs it if you don't control theObjectMapper
.