我是Simple(XML)框架的新手,遇到了序列化特定类构造的问题。
我有两个班级:
@Root(name="static")
class StaticData {
@Attribute
private String id;
@Attribute
private String value;
...
}
和
@Root(name="listdata")
class ListData {
// Problem field
@Attribute
private StaticData ref;
@Element
private String name;
}
收到 " TransformException:不支持类StaticData的转换"。 我希望ListData中的ref-field不要扩展到静态数据XML结构(然后@Element就可以了),但要获得引用。
<listdata ref="foo">
<name>bla bla</name>
</listdata>
其中&#34; foo&#34;是&#34; id&#34;的有效值在我的应用程序中已经加载的一些StaticData对象中。
在JAXB中,我将使用XmlJavaTypeAdapter注释
@XmlAttribute(name="id")
@XmlJavaTypeAdapter(MyStaticDataAdapter.class)
但我似乎无法在Simple中找到一个有效的等效物。
答案 0 :(得分:0)
有疑问您可以使用 Converter 来实施此类行为。
以下是一个例子:
@Root(name = "listdata")
@Convert(ListData.ListDataConverter.class)
class ListData
{
@Attribute
private StaticData ref;
@Element
private String name;
// ...
// Converter implementation
static class ListDataConverter implements Converter<ListData>
{
@Override
public ListData read(InputNode node) throws Exception
{
/*
* In case you also want to read, implement this too ...
*/
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void write(OutputNode node, ListData value) throws Exception
{
node.setAttribute("ref", value.ref.getId());
node.getChild("name").setValue(value.name);
}
}
}
<强>用法:强>
Serializer ser = new Persister(new AnnotationStrategy());
/* ^----- important! -----^ */
ListData ld = ...
ser.write(ld, System.out); // Serialize to std out
<强>输出强>
使用这些ListData
值...
<listdata ref="123">
<name>def</name>
</listdata>