问题描述
我正在尝试反序列化我的 JSON,一切正常,但我想添加一些条件以使其更好。
以下是基于反序列化发生的父类:
public class ParentJSON{
@NotNull
private String name;
private ChildJSON type;
}
字段 type
是可选的,是 JSON。但是,如果字段 type
存在于 JSON 中,那么我想将 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"
}
}
}
解决方法
如果您的父类如下所示,则类型字段将不是必需的:
public class ParentJSON{
@NotNull
private String name;
@Valid
private ChildJSON type;
}
要评估 ChildJSON 约束需要 @Valid 注释。 然后,您可以将 @NotNull 添加到您的 Child 类字段中:
public class ChildJSON{
@NotNull
private String childName;
@NotNull
private String childType;
}
仅当 ParentJSON 类中的 type 字段不为 null 时,才需要 ChildJSON 字段。
此外,如果您希望 JSON 看起来完全一样,您将需要更新您的对象映射器以仅序列化非空字段。
final ObjectMapper objectMapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
注意:确保您为 ParentJSON 类提供了两个构造函数 - 一个带有 type 字段,一个没有它