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 );
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());
}
}
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 );
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();
}
}
Questions:
Thank you.
I have to answer by myself again :-)
Advice from Niall Gallagher, project leader of Simple XML, from support-list:
"You could use either a Converter or a Transform. I would say for a UUID a Transform with a Matcher would be the easiest option."
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 :-)
I think i have the answer to this.
Strategy strategy = new AnnotationStrategy();
Serializer serializer = new Persister(strategy);
should register the converter and solve the problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With