大佬教程收集整理的这篇文章主要介绍了基于Jackson中另一个字段值的条件字段要求?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
您可以使用自定义解串器来实现它。
您的Example
课程如下:
public class Example {
private String type;
private List<Integer> ListA;
private List<Integer> ListB;
// Getters and setters omitted
}
您的自定义解串器可能如下:
public class ExampleDeserializer extends StdDeserializer<Example> {
private static final String TYPE_A = "A";
private static final String TYPE_B = "B";
public ExampleDeserializer() {
super(Example.class);
}
@OverrIDe
public Example deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
ObjectMapper mapper = (ObjectMapper) p.getCodec();
JsonNode tree = mapper.readTree(p);
Example example = new Example();
JsonNode typeNode = tree.get("type");
if (typeNode == null || typeNode.asText().isEmpty()) {
throw ctxt.mapPingException("\"type\" is required");
}
example.setType(typeNode.asText());
switch (typeNode.asText()) {
case TYPE_A:
ArrayNode ListANode = (ArrayNode) tree.get("ListA");
if (ListANode == null || ListANode.size() == 0) {
throw ctxt.mapPingException(
"\"ListA\" is required when \"type\" is \"" + TYPE_A + "\"");
}
example.setListA(createList(ListANode));
break;
case TYPE_B:
ArrayNode ListBNode = (ArrayNode) tree.get("ListB");
if (ListBNode == null || ListBNode.size() == 0) {
throw ctxt.mapPingException(
"\"ListB\" is required when \"type\" is \"" + TYPE_B + "\"");
}
example.setListB(createList(ListBNode));
break;
default:
throw ctxt.mapPingException(
"\"type\" must be \"" + TYPE_A + "\" or \"" + TYPE_B + "\"");
}
return example;
}
private List<Integer> createList(ArrayNode arrayNode) {
List<Integer> List = new ArrayList<Integer>();
for (JsonNode node : arrayNode) {
List.add(node.asInt());
}
return List;
}
}
将上面定义的自定义解串器注册到您的ObjectMapper
:
SimpleModule module = new SimpleModule("ExampleDeserializer",
new Version(1, 0, 0, null, "com.example", "example-deserializer"));
ExampleDeserializer exampleDeserializer = new ExampleDeserializer();
module.addDeserializer(Example.class, exampleDeserializer);
ObjectMapper mapper = new ObjectMapper()
.registerModule(module)
.enable(SerializationFeature.INDENT_OUTPUT);
使用自定义序列化器:
String Json = "{\"type\":\"A\",\"ListA\":[1,2,3]}";
Example example = mapper.readValue(Json, Example.class);
考虑具有一个字符串和两个数组的JSON表示形式。例如,
{
"type" : "A","ListA" : []
"ListB" : [3,4,5]
}
在上述情况下,type
需要现场,但ListA
和ListB
被 有条件地
基于所述值所需的反序列化type
。换句话说,ListA
如果只需要type
有值A
和ListB
如果只要求type
有一个值B
。
当前,我在Jackson和Java中工作,并且能够type
通过创建POJO
以下代码来实现使字段成为强制性的:
public class Example {
@JsonProperty(required = true)
String type;
// getter and setter auto-generated
但我不能只是附加其他@JsonProperty(required = true)
到ListA
或ListB
因为它依赖的价值type
。
我怎么能有条件地要求ListA
和ListB
反序列化基础上的价值type
?
另外,我将要执行额外的检查,例如,是否任一ListA
或ListB
为空数组(size == 0
)或没有。
以上是大佬教程为你收集整理的基于Jackson中另一个字段值的条件字段要求?全部内容,希望文章能够帮你解决基于Jackson中另一个字段值的条件字段要求?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。