[英]Jackson enum deserialization delegation
Is there a way to deserialize an enum which works for both the name and the object notation.有没有办法反序列化适用于名称和对象符号的枚举。 I do want to keep the Shape as object for the deserialization though
我确实希望将 Shape 作为反序列化的对象
eg This works for "type": {"name":"MYENUM"}, but what would I need to add to have it also work for "type": "MYENUM"例如,这适用于“类型”:{“名称”:“MYENUM”},但是我需要添加什么才能使其也适用于“类型”:“MYENUM”
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum MyType {
@JsonProperty("MYENUM")
MYENUM("MyEnum")
public final String name = name();
MyType(String value) {
this.value = value;
}
@JsonCreator
public static MyType deserialize (@JsonProperty("name") String name) {
return MyType.valueOf(name);
}
}
Have tried adding a delegate like this曾尝试添加这样的委托
@JsonCreator(mode=JsonCreator.Mode.DELEGATING)
public static MyType deserializeString (String name) {
return MyType.valueOf(name);
}
One way to solve your problem is a custom deserializer extending StdDeserializer
and inside of it check if your json file is in the form of "type": {"name":"MYENUM"} or {"type": "MYENUM"} .解决您的问题的一种方法是扩展
StdDeserializer
的自定义解串器,并在其中检查您的 json 文件是否采用"type": {"name":"MYENUM"}或{"type": "MYENUM"} 的形式。 This checking can be obtained with the JsonNode.html#isObject
method :可以使用
JsonNode.html#isObject
方法获得此检查:
public class MyTypeDeserializer extends StdDeserializer<MyType> {
public MyTypeDeserializer() {
this(null);
}
public MyTypeDeserializer(Class<?> vc) {
super(vc);
}
@Override
public MyType deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException {
JsonNode root = jp.getCodec().readTree(jp);
JsonNode nodeType = root.get("type");
String name = nodeType.isObject() ? nodeType.get("name").asText() : nodeType.asText();
return MyType.valueOf(name);
}
}
Then you can annotate your MyType
enum with the @JsonDeserialize(using = MyTypeDeserializer.class)
deleting your deserialize
method like below :然后,您可以使用
@JsonDeserialize(using = MyTypeDeserializer.class)
删除您的deserialize
方法来注释您的MyType
枚举,如下所示:
@JsonDeserialize(using = MyTypeDeserializer.class)
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum MyType { //omitted fields and methods for brevity }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.