[英]Jackson serialize simple one attribute ValueObject like Enum - without nesting
Is it possible to configure jackson to serialize simple value objects, wrapping only one attribute, to be serialized like enums?是否可以配置 jackson 序列化简单的值对象,只包装一个属性,像枚举一样序列化?
public final class ErrorCode {
private final String value;
public ErrorCode(@JsonProperty("value") final String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
Now it is serialized as ..., "errorCode":{"value":"invalid.login"}, ...
but I would like to have, as if it were enum, ..., "errorCode":"invalid.login", ...
.现在它被序列化为..., "errorCode":{"value":"invalid.login"}, ...
但我想拥有,就好像它是枚举一样, ..., "errorCode":"invalid.login", ...
It is possible to but only via @ JsonUnwrapped() in each surrounding class可以但只能通过每个周围 class 中的@JsonUnwrapped()
SorroundingClass {
@JsonUnwrapped()
private ErrorCode errorCode;
...
}
I would like to configure It only in one place, best in ErrorCode itself.我只想在一个地方配置它,最好在 ErrorCode 本身。
Looking at flattening-nested-attributes-in-jackson it seems to me impossible, but I want to make sure.看着flattening-nested-attributes-in-jackson在我看来这是不可能的,但我想确定一下。
You can achieve this by implementing custom com.fasterxml.jackson.databind.JsonSerializer
serializer:您可以通过实现自定义com.fasterxml.jackson.databind.JsonSerializer
序列化程序来实现这一点:
class SingleValueJsonSerializer extends JsonSerializer<Object> {
@Override
public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
if (value == null) {
gen.writeNull();
return;
}
final Field[] fields = value.getClass().getDeclaredFields();
if (fields.length != 1) {
throw new IOException("Do not use this serialiser for the class " + value.getClass().getSimpleName() + " which has" + fields.length + " fields!");
}
final Field first = fields[0];
try {
final Object fieldValue = first.get(value);
gen.writeObject(fieldValue);
} catch (IllegalAccessException e) {
throw new IOException(e);
}
}
}
You can define it in required class:您可以在所需的 class 中定义它:
class Wrapper {
@JsonSerialize(using = SingleValueJsonSerializer.class)
private ErrorCode error;
// other fields
}
or register it globally by defining on the class level:或通过在 class 级别上定义来全局注册它:
@JsonSerialize(using = SingleValueJsonSerializer.class)
class ErrorCode {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.