杰克逊(Jackson)处理字符串(如果有注释) [英] Jackson process string if annotated
问题描述
如果该字段具有注释,则需要替换所有&反序列化时,字符串中带有§的字符,而序列化时则相反.
If the field has an annotation, I need to replace all the & characters in the string with § when deserializing, and do the opposite when serializing
例如,我创建了一个注释并用它标记了一个字段
For example i created an annotation and marked a field with it
public class SomeData {
@MinecraftColorText
private String str;
}
我需要阅读此json:
I need read this json:
{"str":"&6Some nice text"}
,并且在Java对象中,str字段需要为:§6一些漂亮的文本
and in java object str field need be: §6Some nice text
我只需要处理带注释的字段,而不是全部字符串
Im need process only annotated fields, not all String
我想用 ContextualSerializer
做到这一点,但是据我了解,它取代了标准的序列化
I wanted to do it with ContextualSerializer
, but as I understand it, it replaces the standard serialization
推荐答案
因此,您应该更改自定义批注 @MinecraftColorText
并添加序列化和反序列化转换器:
So you should change your custom annotation @MinecraftColorText
and add serialize and deserialize convertors:
@JsonDeserialize(converter = MinecraftDeserializeConverter.class)
@JsonSerialize(converter = MinecraftSerializeConverter.class)
@Retention(RUNTIME)
@Target(FIELD)
@JacksonAnnotationsInside
public @interface MinecraftColorText {
}
反序列化转换器:
public class MinecraftDeserializeConverter extends StdConverter<String, String> {
@Override
public String convert(final String s) {
return s.replaceAll("&", "§");
}
}
序列化转换器:
public class MinecraftSerializeConverter extends StdConverter<String, String> {
@Override
public String convert(final String s) {
return s.replaceAll("§", "&");
}
}
并使用:
@MinecraftColorText
private String str;
p.s:不要忘记将 @JacksonAnnotationsInside
通知 jackson
有关您的自定义序列化操作的信息.在此处
p.s: Don't forget about @JacksonAnnotationsInside
that notify jackson
about your custom serialization action.
See more here
这篇关于杰克逊(Jackson)处理字符串(如果有注释)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!