Created
May 13, 2015 14:44
-
-
Save vshank77/04f10473265e91d8386c to your computer and use it in GitHub Desktop.
Serialize ImmutableList with GSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class JsonSerializerTest { | |
@Test | |
public void testGsonInterpret() throws Exception { | |
Definition expected = Definition.builder().domain("places").traitName("TrainStation") | |
.desc("london underground").tag("lgu").tag("tube").tag("tfl") | |
.property(Property.builder("name", StringTraitRef)) | |
.property(Property.builder("age", IntegerTraitRef)) | |
.build(); | |
Gson gson = new GsonBuilder() | |
.registerTypeAdapter(ImmutableList.class, new ImmutableListDeser()) | |
.registerTypeAdapter(ImmutableSortedSet.class, new ImmutableSortedSetDeser()) | |
.create(); | |
String json = gson.toJson(expected); | |
System.out.println(json); | |
Definition actual = gson.fromJson(json, Definition.class); | |
assertEquals(expected, actual); | |
} | |
static class ImmutableListDeser implements JsonDeserializer<ImmutableList<?>> { | |
@Override | |
public ImmutableList<?> deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { | |
final Type type2 = ParameterizedTypeImpl.make(List.class, ((ParameterizedType) type).getActualTypeArguments(), null); | |
final List<?> list = context.deserialize(json, type2); | |
return ImmutableList.copyOf(list); | |
} | |
} | |
static class ImmutableSortedSetDeser implements JsonDeserializer<ImmutableSortedSet<?>> { | |
@Override | |
public ImmutableSortedSet<?> deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { | |
final Type type2 = ParameterizedTypeImpl.make(SortedSet.class, ((ParameterizedType) type).getActualTypeArguments(), null); | |
final SortedSet<?> set = context.deserialize(json, type2); | |
return ImmutableSortedSet.copyOf(set); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment