discomarathon / google-gson

Automatically exported from code.google.com/p/google-gson
0 stars 0 forks source link

java.util.UUID should be supported out of the box (just like URL and URI do) #79

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
Add tests:
    public void testUuidSerialization() throws Exception {
        String uuidValue = "c237bec1-19ef-4858-a98e-521cf0aad4c0";
        UUID uuid = UUID.fromString(uuidValue);
        assertEquals('"' + uuidValue + '"', gson.toJson(uuid));
    }

    public void testUuidDeserialization() {
        String uuidValue = "c237bec1-19ef-4858-a98e-521cf0aad4c0";
        String json = '"' + uuidValue + '"';
        UUID target = gson.fromJson(json, UUID.class);
        assertEquals(uuidValue, target.toString());
    }

Suggestion of how to implement type adapter:

  private static class UuidTypeAdapter implements JsonSerializer<UUID>,
JsonDeserializer<UUID>,
    InstanceCreator<UUID> {

    public JsonElement serialize(UUID src, Type typeOfSrc,
JsonSerializationContext context) {
        return new JsonPrimitive(src.toString());
    }

    public UUID deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) 
    throws JsonParseException {     
        return UUID.fromString(json.getAsString());
    }

    public UUID createInstance(Type type) {     
        return new UUID(0, 0);
    }
    @Override
    public String toString() {
        return UuidTypeAdapter.class.getSimpleName();
    }
  }

Original issue reported on code.google.com by heg...@gmail.com on 9 Dec 2008 at 11:56

GoogleCodeExporter commented 9 years ago
This seems reasonable to me!

I am going to take your suggested implementation and modify it ever so 
slightly. 
This is because the next release of Gson will not longer require an 
"InstanceCreator"
when a custom deserializer is registered (i.e. Issue #69).

Thanks for the suggestion and implementation :)

Original comment by joel.leitch@gmail.com on 13 Dec 2008 at 8:36

GoogleCodeExporter commented 9 years ago
Default support for UUID implemented in r327.

Original comment by joel.leitch@gmail.com on 13 Dec 2008 at 8:45