我有这个带JAXB注释的类:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class SomeClass {
@XmlAttribute
public String value;
}
基于此类,使用jersey-json(通过com.sun.jersey.api.json.JSONJAXBContext
)生成JSON文档:
{
"@value":"someValue"
}
请注意,泽西决定使用@value
作为标记名称(而不仅仅是value
),这可能是为了兑现@XmlAttribute
注释。
现在的任务是使用jackson-json读取这个json文档并生成一个JAXB注释类的实例:
ObjectMapper mapper = new ObjectMapper();
JaxbAnnotationIntrospector introspector = new JaxbAnnotationIntrospector(mapper.getTypeFactory());
DeserializationConfig deserConfig = mapper.getDeserializationConfig().with(introspector);
mapper.setConfig(deserConfig);
SerializationConfig serConfig = mapper.getSerializationConfig().with(introspector);
mapper.setConfig(serConfig);
mapper.readValue(jsonFile, SomeClass.class);
此操作失败,但出现以下异常:
Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "@value" (class test.jersey.vs.jackson.SomeClass), not marked as ignorable (one known property: "value"])
at [Source: C:\Users\AppData\Local\Temp\junit5080915042527904512\json.txt; line: 1, column: 12] (through reference chain: test.jersey.vs.jackson.SomeClass["@value"])
at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:62)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnknownProperty(DeserializationContext.java:834)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1093)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1477)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1455)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:282)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:140)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3798)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2740)
我现在的问题是,是否有办法告诉jackson将JSON文档中的@value
标记与该类的value
字段相关联。
我尝试指定PropertyNamingStrategy
,但在反序列化期间从未调用过。
PropertyNamingStrategy pns = new PropertyNamingStrategy() {
@Override
public String nameForField(MapperConfig<?> config, AnnotatedField field, String defaultName) {
if (field.hasAnnotation(XmlAttribute.class)) {
if (defaultName.startsWith("@")) {
return defaultName.substring(1);
}
}
return super.nameForField(config, field, defaultName);
}
};
DeserializationConfig deserConfig = mapper.getDeserializationConfig().with(introspector).with(pns);
mapper.setConfig(deserConfig);