views:

93

answers:

1

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:

  • Is custom Matcher always recommended practice for streaming third-party classes?
  • In which case I can use Converter?
  • Are there any better tutorials/examples for Simple XML out there?

Thank you.

A: 

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<T> or a Transform<T>. I would say 
 for a UUID a Transform<T> 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 :-)

mschayna
Again, accepting for completeness.
mschayna