gpt4 book ai didi

java - @JsonFormat 不适用于自定义序列化器

转载 作者:行者123 更新时间:2023-12-02 09:06:19 26 4
gpt4 key购买 nike

我有一些特殊的业务,需要一个自定义序列化器,它在修改 DictAnnotation 注释的字段中添加一个字段,它可以工作。
@JsonFormat 不起作用。我的 createTime 字段曾经是这样的:

"createTime":"2019-12-12"

现在:

"createTime":1577835397615

DictAnnotation没有修改的字段都使用了默认的JsonSerializer,所以不知道问题出在哪里。

我的主要代码如下:

绑定(bind)自定义SerializerModifier

@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
SimpleModule simpleModule = new SimpleModule().setSerializerModifier(new DictSerializerModifier());
builder.modules(simpleModule);
return builder;
}

自定义序列化器修改器

public class DictSerializerModifier extends Jdk8BeanSerializerModifier {
@Override
public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) {
return new DictSerializer(null, (JsonSerializer<Object>) serializer);
}
}

自定义序列化器

public class DictSerializer extends JsonSerializer<Object> implements ContextualSerializer {

private static final String MY_BIZ_FIELD_SUFFIX = "_test";
private DictAnnotation.ElementType type;
private JsonSerializer<Object> defSerializer;

public DictSerializer(DictAnnotation.ElementType type, JsonSerializer<Object> jsonSerializer) {
this.defSerializer = jsonSerializer;
this.type = type;
}

@Override
public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) {
// my biz annotation
DictAnnotation.ElementType elementType = Optional.ofNullable(property).map(b -> b.getAnnotation(DictAnnotation.class))
.map(d -> d.type()).orElse(null);
// if null, use defSerializer
return elementType == null ? defSerializer : new DictSerializer(elementType, defSerializer);
}

@Override
public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
defSerializer.serialize(value, gen, serializers);
if (type != null) {
String fieldName = gen.getOutputContext().getCurrentName();
String codeLabel = RedisUtils.dictCodeToLabel(type, value.toString());
gen.writeStringField(fieldName.concat(MY_BIZ_FIELD_SUFFIX), codeLabel);
}
}
}

测试pojo类

public class TestVo {

@DictAnnotation(type = A)
private String aCode;

@DictAnnotation(type = B)
private String bCode;

@DictAnnotation(type = C)
private String cCode;

@JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
private Date createTime;
getter.... settter...

期待您的指导!

最佳答案

您可以尝试一下是否有帮助(添加@JsonSerialize,如下所述)

@JsonSerialize(as = Date.class)
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
private Date createTime;

关于java - @JsonFormat 不适用于自定义序列化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59549259/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com