我正在尝试反序列化我的JSON,一切都很好,但我想添加一些条件来使其更好。
下面是我的父类,反序列化是基于这个父类实现的:
public class ParentJSON{
@NotNull
private String name;
private ChildJSON type;
}字段type是可选的是JSON。但是,如果JSON中存在字段type,那么我希望将ChildJSON中的字段设置为必填字段:
public class ChildJSON{
private String childName;
private String childType;
}如果我直接将@NotNull添加到我的ChildJSON字段中,那么如果type不在JSON中,它将抛出错误。
下面是我的客户端文件,它将读取JSONFILE:
public class Client {
public static void main(String args[]) {
final ObjectMapper objectMapper = new ObjectMapper();
ParentJSON json = objectMapper.readValue(ApplicationMain.class.getResourceAsStream("/JSONFile.json"), ParentJSON.class);
}
}我的json看起来像这样:
{
{
"name":"Hello"
},
{
"name":"Bye",
"type":{
"childName":"childByeName",
"childType":"childByeType"
}
}
}发布于 2021-01-19 22:04:35
如果您的父类如下所示,则type字段将不是必填字段:
public class ParentJSON{
@NotNull
private String name;
@Valid
private ChildJSON type;
}@Valid注释是计算ChildJSON约束所必需的。然后,您可以将@NotNull添加到您的子类字段:
public class ChildJSON{
@NotNull
private String childName;
@NotNull
private String childType;
}仅当ParentJSON类中的类型字段不为空时,才需要ChildJSON字段。
此外,如果希望JSON看起来与非空字段完全一样,则需要更新对象映射器以仅序列化非空字段。
final ObjectMapper objectMapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);注意:请确保为ParentJSON类提供了两个构造函数-一个有类型字段,另一个没有类型字段
https://stackoverflow.com/questions/65791121
复制相似问题