问题描述
我决定使用,并且遇到了基本问题。我试图将 java.util.UUID
类实例序列化为这个小类中的最后一个字段:
I have decided to use Simple XML serialization and was stucked with basic problem. I am trying to serialize java.util.UUID
class instance as final field in this small class:
@Root
public class Identity {
@Attribute
private final UUID id;
public Identity(@Attribute UUID id) {
this.id = id;
}
}
显示了如何通过注册这样的转换器来序列化第三方对象:
Tutorial shows how to serialize third-party objects by registering converters like this:
Registry registry = new Registry();
registry.bind(UUID.class, UUIDConverter.class);
Strategy strategy = new RegistryStrategy(registry);
Serializer serializer = new Persister(strategy);
serializer.write( object, stream );
适用于UUID的转换器非常简单:
appropriate converter for UUID is pretty simple:
public class UUIDConverter implements Converter<UUID> {
@Override
public UUID read(InputNode node) throws Exception {
return new UUID.fromString(node.getValue());
}
@Override
public void write(OutputNode node, UUID value) throws Exception {
node.setValue(value.toString());
}
}
但是这个简单的代码对我来说不起作用,在序列化期间,具有UUID字段的对象被抛出异常不支持类java.util.UUID的变换。
But this simple code just didn't work for me, during serialization objects with UUID fields was thrown exception Transform of class java.util.UUID not supported.
我尝试了类似的东西自定义匹配器
(不在教程中)对我有用:
I have tried something something similar with custom Matcher
(which was not in tutorial) that works for me:
Serializer serializer = new Persister(new MyMatcher());
serializer.write( object, stream );
和 Matcher
类看起来像这样: / p>
and Matcher
class looks like this:
public static class MyMatcher implements Matcher {
@Override
@SuppressWarnings("unchecked")
public Transform match(Class type) throws Exception {
if (type.equals(UUID.class))
return new UUIDTransform();
return null;
}
}
public class UUIDTransform implements Transform<UUID> {
@Override
public UUID read(String value) throws Exception {
return UUID.fromString(value);
}
@Override
public String write(UUID value) throws Exception {
return value.toString();
}
}
问题:
- 自定义匹配器总是推荐用于流式传输第三方类吗?
- 在哪种情况下我可以使用Converter?
- 有没有更好的Simple XML教程/示例?
谢谢。
推荐答案
我必须自己回答再次: - )
I have to answer by myself again :-)
来自支持列表的Simple XML项目负责人Niall Gallagher的建议:
Advice from Niall Gallagher, project leader of Simple XML, from support-list:
所以,我使用转换< T>
/ 匹配器
和对此感到满意。这并没有改变转换器< T>
对我不起作用的事实: - )
So, I use Transform<T>
/Matcher
and satisfied with it. This does not alter the fact that the Converter<T>
does not work for me :-)
这篇关于使用Simple XML(org.simpleframework.xml)序列化第三方类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!