通过 JAXB 为枚举提供自定义值序列化 [英] Providing custom value serialization for enums via JAXB
问题描述
对于我正在处理的一个项目,我们使用了很多枚举.模型对象本身由许多小类组成;然后我们通过 JAXB 将此模型作为 XML 序列化到我们的数据库.现在,我们希望能够使用枚举中特定方法的返回来序列化我们的枚举值;给出的:
For a project I'm working on, we have a lot of enums in use. The model object itself is composed from a lot of tiny classes; this model we then serialize to our DB as XML via JAXB. Now, we want to be able to serialize our enum values using the return of a particular method in the enum; that is given:
public enum Qualifier {
FOO("1E", "Foo type document"),
BAR("2", "Bar object");
private String code, description;
public Qualifier(String code, String description) {
this.code = code;
this.description = description;
}
public String getCode() {
return this.code;
}
public String getDescription() {
return this.description;
}
}
等等.等等.目前,当序列化为 XML 时,我们得到如下内容:
etc. etc. Currently, when serialized to XML, we get something like:
<qualifier>FOO</qualifier>
这就是 JAXB 处理它的方式.然而,我们需要该值是 getCode() 的返回值,并且我们的大量枚举确实遵循该约定(具有用于通过代码查找的相应静态方法),因此上述 XML 片段如下所示:
which is how JAXB handles it. However, we need the value to be the return of getCode(), and a whole lot of our enums do follow that convention (with a corresponding static method for lookup via code), so that the above XML fragment looks like:
<qualifier>1E</qualifier>
相反.我们可以用@XmlEnum
和@XmlEnumValue
来注释它,但这太繁琐了——有些枚举最多有30 个枚举值,手工编辑也不好.我们也在考虑使用自定义序列化程序,但我现在不想走这条路(但如果这是要走的路,那么我没有问题).
instead. We can annotate it with @XmlEnum
and @XmlEnumValue
, but that's too tedious -- some enums have up to 30 enumerated values, and hand-editing it is not good. We're also thinking of using a custom serializer instead, but I'd like to avoid going that route for now (but if that's the way to go, then I have no problem with it).
有什么想法吗?
推荐答案
为此尝试使用 XmlAdapter
机制.您为每个枚举类型创建一个 XmlAdapter
子类,该子类知道如何将枚举编组/解组为 XML.
Try using the XmlAdapter
mechanism for this. You create an XmlAdapter
subclass for each enum type, and which knows how to marshal/unmarshal the enum to and from XML.
然后您将适配器与属性相关联,例如
You then associate the adapter with the property, e.g.
public class QualifierAdapter extends XmlAdapter<String, Qualifier> {
public String marshal(Qualifier qualifier) {
return qualifier.getCode();
}
public Qualifier unmarshal(String val) {
return Qualifier.getFromCode(val); // I assume you have a way of doing this
}
}
然后在模型类中:
@XmlJavaTypeAdapter(QualifierAdapter.class)
private Qualifier qualifier;
您也可以在包级别声明这一点,在与模型类相同的包中的一个名为 package-info.java
的文件中,使用相当特殊的包注释:
You can also declare this at the package level, inside a file called package-info.java
in the same package as your model classes, using the rather idiosyncratic package annotations:
@javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters({
@javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter(
type=Qualifier.class, value=QualifierAdapter.class
)
})
package com.xyz;
这篇关于通过 JAXB 为枚举提供自定义值序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!