我正在使用遗留系统,其中数据基本上保存为非规范化格式。最糟糕的是,没有使用一致的命名策略。取下面的对象基本上包含两个地址(但可能更多):
{
"studentAddress": "123 new Street",
"studentCity": "New City",
"studentState_w": "NY",
"studentZip": "11220",
"teacherAddress:: "424 main st",
"teacherCity_txt": "Summerville",
"teacherState_x" : "NJ",
"teacherZip": "13454",
...
...
}
我希望能够序列化/反序列化为以下对象:
public class SomeData {
Address teacher;
Address student;
public static class Address {
String address;
String city;
String state;
String zipcode;
}
}
我的想法是像这样创建一个自定义注释AddressMapper
public @interface AddressMapper {
String addressField () default "address",
String cityField () default "city",
String stateField () default "state",
String zipField () default "zipcode"
}
然后在类上使用它:
public class SomeData {
@AddressMapper (addressField="teacherAddress", cityField="teacherCity_txt", stateField="studentState_w", zipField="teacherZip")
@JsonSerialize(using = AddressSerializer.class)
Address teacher;
@AddressMapper (addressField="studentAddress", cityField="studentCity", stateField="studentState_w", zipField="studentZip")
@JsonSerialize(using = AddressSerializer.class)
Address student;
}
但是,我找不到从序列化方法获取@AddressMapper注释的方法
public class AddressMapper extends JsonSerializer<Address> {
public void serialize(Address value, JsonGenerator jgen, SerializerProvider provider) {
//How to i get field annotation????
}
}
如何在此处获取字段注释的实例?还有另一种方法可以解决这个问题吗?
答案 0 :(得分:0)
实现此目的的方法是实现ContextualDeserializer来读取注释。在jackson的测试用例中可以找到一个例子: https://github.com/FasterXML/jackson-databind/blob/master/src/test/java/com/fasterxml/jackson/databind/contextual/TestContextualSerialization.java
然而,反序列化对象将具有挑战性。
答案 1 :(得分:0)
基本上你需要实现ContextualSerializer
@Override
public JsonSerializer<?> createContextual(final SerializerProvider prov, final BeanProperty property) throws JsonMappingException {
String[] field = null;
JsonAlias ann = null;
if (property != null) {
ann = property.getAnnotation(JsonAlias.class);
}
if (ann != null) {
field = ann.value();
}
return new JsoinAliasSerializer(field);
}