尽管正如其他人指出的那样很难管理,但您可以做您想做的事。添加自定义解串器来处理这种情况。我重写了你的 bean,因为我觉得你的 Attribute 类有点误导。对象中的 AttributeEntry 类是该“属性”列表中的条目。 ValueObject 是表示“键”/“标签”对象的类。这些 bean 位于下面,但这是自定义反序列化器。这个想法是检查 JSON 中的类型,并根据其“值”类型实例化适当的 AttributeEntry。
public class AttributeDeserializer extends JsonDeserializer<AttributeEntry> {
@Override
public AttributeEntry deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
JsonNode root = p.readValueAsTree();
String name = root.get("name").asText();
if (root.get("value").isObject()) {
// use your object mapper here, this is just an example
ValueObject attribute = new ObjectMapper().readValue(root.get("value").asText(), ValueObject.class);
return new AttributeEntry(name, attribute);
} else if (root.get("value").isTextual()) {
String stringValue = root.get("value").asText();
return new AttributeEntry(name, stringValue);
} else {
return null; // or whatever
}
}
}
由于这种不明确的类型带来的不便,您必须在整个代码库中进行一些类型检查。
然后,您可以将此自定义反序列化器添加到对象映射器中,如下所示:
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addDeserializer(AttributeEntry.class, new AttributeDeserializer());
objectMapper.registerModule(simpleModule);
这是属性条目:
public class AttributeEntry {
private String name;
private Object value;
public AttributeEntry(String name, String value) {
this.name = name;
this.value = value;
}
public AttributeEntry(String name, ValueObject attributes) {
this.name = name;
this.value = attributes;
}
/* getters/setters */
}
这是值对象:
public class ValueObject {
private String key;
private String label;
/* getters/setters */
}