Skip to content

Instantly share code, notes, and snippets.

@vshank77
Created May 13, 2015 14:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vshank77/04f10473265e91d8386c to your computer and use it in GitHub Desktop.
Save vshank77/04f10473265e91d8386c to your computer and use it in GitHub Desktop.
Serialize ImmutableList with GSON
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