From fc99556f22b476057f95c04a1648b3bbddc130b5 Mon Sep 17 00:00:00 2001 From: Jesse Wilson Date: Fri, 5 Aug 2011 00:25:49 +0000 Subject: [PATCH] Support type exclusion strategies. --- gson/src/main/java/com/google/gson/Gson.java | 17 +++++++++++++++-- .../google/gson/internal/bind/TypeAdapters.java | 10 ++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/gson/src/main/java/com/google/gson/Gson.java b/gson/src/main/java/com/google/gson/Gson.java index 134215ed..37c6ba55 100644 --- a/gson/src/main/java/com/google/gson/Gson.java +++ b/gson/src/main/java/com/google/gson/Gson.java @@ -164,8 +164,8 @@ public final class Gson { false, LongSerializationPolicy.DEFAULT); } - Gson(ExclusionStrategy deserializationExclusionStrategy, - ExclusionStrategy serializationExclusionStrategy, + Gson(final ExclusionStrategy deserializationExclusionStrategy, + final ExclusionStrategy serializationExclusionStrategy, final FieldNamingStrategy2 fieldNamingPolicy, final MappedObjectConstructor objectConstructor, boolean serializeNulls, final ParameterizedTypeHandlerMap> serializers, @@ -208,6 +208,18 @@ public final class Gson { } }; + TypeAdapter.Factory excludedTypeFactory = new TypeAdapter.Factory() { + @Override public TypeAdapter create(MiniGson context, TypeToken type) { + Class rawType = type.getRawType(); + if (serializationExclusionStrategy.shouldSkipClass(rawType) + || deserializationExclusionStrategy.shouldSkipClass(rawType)) { + return TypeAdapters.EXCLUDED_TYPE_ADAPTER; + } else { + return null; + } + } + }; + MiniGson.Builder builder = new MiniGson.Builder() .withoutDefaultFactories() .factory(TypeAdapters.BOOLEAN_FACTORY) @@ -219,6 +231,7 @@ public final class Gson { .factory(TypeAdapters.newFactory(long.class, Long.class, longAdapter(longSerializationPolicy))) .factory(TypeAdapters.STRING_FACTORY) + .factory(excludedTypeFactory) .factory(new GsonToMiniGsonTypeAdapter(serializers, deserializers, serializeNulls)) .factory(CollectionTypeAdapter.FACTORY) .factory(StringToValueMapTypeAdapter.FACTORY) diff --git a/gson/src/main/java/com/google/gson/internal/bind/TypeAdapters.java b/gson/src/main/java/com/google/gson/internal/bind/TypeAdapters.java index c6e6566c..3518122a 100644 --- a/gson/src/main/java/com/google/gson/internal/bind/TypeAdapters.java +++ b/gson/src/main/java/com/google/gson/internal/bind/TypeAdapters.java @@ -98,6 +98,16 @@ public final class TypeAdapters { public static final TypeAdapter.Factory STRING_FACTORY = newFactory(String.class, STRING); + public static final TypeAdapter EXCLUDED_TYPE_ADAPTER = new TypeAdapter() { + @Override public Object read(JsonReader reader) throws IOException { + reader.skipValue(); + return null; + } + @Override public void write(JsonWriter writer, Object value) throws IOException { + writer.nullValue(); + } + }; + public static TypeAdapter.Factory newFactory( final TypeToken type, final TypeAdapter typeAdapter) { return new TypeAdapter.Factory() {