request for java.util.UUID support

Issue #306 resolved
The Alchemist created an issue

It would be cool to automatically support java.util.UUID fields.

Currently, I use this:

public class UUIDConstructor extends Constructor {
    public UUIDConstructor() {
        yamlClassConstructors.put(NodeId.scalar, new UUIDConstruct());
    }

    class UUIDConstruct extends Constructor.ConstructScalar {
        @Override
        public Object construct(Node nnode) {
            if (nnode.getTag().equals(Tag.STR)) {
                Construct dateConstructor = yamlConstructors.get(Tag.STR);
                String date = (String) dateConstructor.construct(nnode);
                try {
                    return UUID.fromString(date);
                } catch (IllegalArgumentException e) {
                    return super.construct(nnode);
                }
            } else {
                return super.construct(nnode);
            }
        }

    }
}

Thanks!

Comments (8)

  1. Andrey Somov

    Can you please be more specific when you say "automatically support java.util.UUID" ? UUID is not defined in the YAML 1.1 specification.

    Your solution is good enough to be used. You may also check Implicit types in the documentation.

  2. The Alchemist reporter

    @@asomov : What I mean by "automatically support java.util.UUID" is this:

    If my YAML looks like this:

    uuid: de305d54-75b4-431b-adb2-eb6b9e546014
    

    ...and the Java bean looks like this:

    class Bean {
        private java.util.UUID uuid;
        /* insert setter and getter for 'uuid' here */
    }
    

    then the marshalling/unmarshalling should automatically work. It currently doesn't because java.util.UUID doesn't have a constructor that accepts a java.lang.String, and you have to use the java.util.UUID.fromString() method.

    I hope that clears things up. I also realized that that variable called 'date' should be called 'uuid' in the example above. :)

  3. Andrey Somov
    • changed status to open

    I think this is a very valid point. But it should be wider: how to provide a factory method for a known class to create instances from scalars. Let us see what we can do. Do you have a proposal how the API may be adapted ?

  4. Andrey Somov
  5. Log in to comment