下面列出了怎么用com.google.gson.TypeAdapterFactory的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
protected void configure() {
bindSetOf(TypeAdapterFactory.class)
.addBinding()
.toInstance(createConditionConfigSerializer());
bindSetOf(TypeAdapterFactory.class)
.addBinding()
.toInstance(createActionConfigSerializer());
bindSetOf(new TypeLiteral<TypeAdapter<?>>() {})
.addBinding()
.to(AttributeTypeAdapter.class)
.asEagerSingleton();
bindSetOf(new TypeLiteral<TypeAdapter<?>>() {})
.addBinding()
.to(TemplatedExpressionTypeAdapter.class)
.asEagerSingleton();
}
private TypeAdapterFactory createConditionConfigSerializer() {
return
RuntimeTypeAdapterFactory
.of(ConditionConfig.class, ATT_TYPE)
.registerSubtype(ContextQueryConfig.class, ContextQueryConfig.TYPE)
.registerSubtype(DayOfWeekConfig.class, DayOfWeekConfig.TYPE)
.registerSubtype(DurationConfig.class, DurationConfig.TYPE)
.registerSubtype(OrConfig.class, OrConfig.TYPE)
.registerSubtype(QueryChangeConfig.class, QueryChangeConfig.TYPE)
.registerSubtype(IfConditionConfig.class, IfConditionConfig.TYPE)
.registerSubtype(ReceivedMessageConfig.class, ReceivedMessageConfig.TYPE)
.registerSubtype(ReferenceFilterConfig.class, ReferenceFilterConfig.TYPE)
.registerSubtype(ThresholdConfig.class, ThresholdConfig.TYPE)
.registerSubtype(TimeOfDayConfig.class, TimeOfDayConfig.TYPE)
.registerSubtype(ValueChangeConfig.class, ValueChangeConfig.TYPE)
;
}
@Override
protected void configure() {
bind(com.iris.io.json.JsonSerializer.class).to(GsonSerializerImpl.class);
bind(com.iris.io.json.JsonDeserializer.class).to(GsonDeserializerImpl.class);
Multibinder
.newSetBinder(binder(), new TypeLiteral<com.google.gson.JsonSerializer<?>>() {})
.addBinding()
.to(AttributeMapSerializer.class);
Multibinder
.newSetBinder(binder(), new TypeLiteral<com.google.gson.JsonDeserializer<?>>() {})
.addBinding()
.to(AttributeMapSerializer.class);
Multibinder
.newSetBinder(binder(), new TypeLiteral<TypeAdapter<?>>() {})
.addBinding()
.to(ByteArrayToBase64TypeAdapter.class);
Multibinder
.newSetBinder(binder(), new TypeLiteral<TypeAdapterFactory>() {})
.addBinding()
.to(TypeTypeAdapterFactory.class);
}
public static <TT> TypeAdapterFactory newEnumTypeHierarchyFactory() {
return new TypeAdapterFactory() {
@SuppressWarnings({"unchecked"})
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
Class<? super T> rawType = typeToken.getRawType();
if (!Enum.class.isAssignableFrom(rawType) || rawType == Enum.class) {
return null;
}
if (!rawType.isEnum()) {
rawType = rawType.getSuperclass(); // handle anonymous subclasses
}
return (TypeAdapter<T>) new EnumTypeAdapter(rawType);
}
};
}
private TypeAdapterFactory createActionConfigSerializer() {
return
RuntimeTypeAdapterFactory
.of(ActionConfig.class, ATT_TYPE)
.registerSubtype(SendActionConfig.class, SendActionConfig.TYPE)
.registerSubtype(SendNotificationActionConfig.class, SendNotificationActionConfig.TYPE)
.registerSubtype(SetAttributeActionConfig.class, SetAttributeActionConfig.TYPE)
.registerSubtype(ForEachModelActionConfig.class, ForEachModelActionConfig.TYPE)
.registerSubtype(LogActionConfig.class, LogActionConfig.TYPE)
.registerSubtype(ActionListConfig.class, ActionListConfig.TYPE);
}
@Override
protected void configure() {
bindSetOf(TypeAdapterFactory.class)
.addBinding()
.toInstance(createActionConfigSerializer());
bindSetOf(new TypeLiteral<TypeAdapter<?>>() {})
.addBinding()
.toInstance(new AttributeTypeAdapter());
bindSetOf(new TypeLiteral<TypeAdapter<?>>() {})
.addBinding()
.toInstance(new TemplatedExpressionTypeAdapter());
}
public void testSerializeCollidingTypeFieldName() {
TypeAdapterFactory billingAdapter = RuntimeTypeAdapterFactory.of(BillingInstrument.class, "cvv")
.registerSubtype(CreditCard.class);
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(billingAdapter)
.create();
try {
gson.toJson(new CreditCard("Jesse", 456), BillingInstrument.class);
fail();
} catch (JsonParseException expected) {
}
}
@SuppressWarnings({ "unchecked", "rawtypes" }) // Casts guarded by conditionals.
TypeAdapter<?> getTypeAdapter(ConstructorConstructor constructorConstructor, Gson gson,
TypeToken<?> type, JsonAdapter annotation) {
Object instance = constructorConstructor.get(TypeToken.get(annotation.value())).construct();
TypeAdapter<?> typeAdapter;
if (instance instanceof TypeAdapter) {
typeAdapter = (TypeAdapter<?>) instance;
} else if (instance instanceof TypeAdapterFactory) {
typeAdapter = ((TypeAdapterFactory) instance).create(gson, type);
} else if (instance instanceof JsonSerializer || instance instanceof JsonDeserializer) {
JsonSerializer<?> serializer = instance instanceof JsonSerializer
? (JsonSerializer) instance
: null;
JsonDeserializer<?> deserializer = instance instanceof JsonDeserializer
? (JsonDeserializer) instance
: null;
typeAdapter = new TreeTypeAdapter(serializer, deserializer, gson, type, null);
} else {
throw new IllegalArgumentException("Invalid attempt to bind an instance of "
+ instance.getClass().getName() + " as a @JsonAdapter for " + type.toString()
+ ". @JsonAdapter value must be a TypeAdapter, TypeAdapterFactory,"
+ " JsonSerializer or JsonDeserializer.");
}
if (typeAdapter != null && annotation.nullSafe()) {
typeAdapter = typeAdapter.nullSafe();
}
return typeAdapter;
}
@Provides
public GsonFactory gson(
Set<TypeAdapterFactory> typeAdapterFactories,
Set<TypeAdapter<?>> typeAdapters,
Set<JsonSerializer<?>> serializers,
Set<JsonDeserializer<?>> deserializers
) {
return new GsonFactory(typeAdapterFactories, typeAdapters, serializers, deserializers, serializeNulls);
}
public ReflectiveTypeAdapter(
Gson gson,
TypeAdapterFactory skipPast,
TypeToken<T> token
) {
this.gson = gson;
this.token = token;
}
public GsonFactory(
Set<TypeAdapterFactory> typeAdapterFactories,
Set<TypeAdapter<?>> typeAdapters,
Set<JsonSerializer<?>> serializers,
Set<JsonDeserializer<?>> deserializers
) {
this(typeAdapterFactories, typeAdapters, serializers, deserializers, true);
}
public GsonFactory(
Set<TypeAdapterFactory> typeAdapterFactories,
Set<TypeAdapter<?>> typeAdapters,
Set<JsonSerializer<?>> serializers,
Set<JsonDeserializer<?>> deserializers,
boolean serializeNulls
) {
this.gson = create(typeAdapterFactories, typeAdapters, serializers, deserializers, serializeNulls);
}
@Provides
GsonBuilder gsonBuilder(Set<TypeAdapterFactory> factories, Map<Type, Object> adapters, Map<Class, Object> hiearchyAdapters) {
GsonBuilder builder = new GsonBuilder()
.setDateFormat(ISO8601_DATE_FORMAT)
.serializeSpecialFloatingPointValues() // Infinity and NaN
.serializeNulls(); // Needed so we can clear fields in PartialModel document updates
factories.forEach(builder::registerTypeAdapterFactory);
adapters.forEach(builder::registerTypeAdapter);
hiearchyAdapters.forEach(builder::registerTypeHierarchyAdapter);
return builder;
}
public static <TT> TypeAdapterFactory newEnumTypeHierarchyFactory() {
return new TypeAdapterFactory() {
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
Class<? super T> rawType = typeToken.getRawType();
if (!Enum.class.isAssignableFrom(rawType) || rawType == Enum.class) {
return null;
}
if (!rawType.isEnum()) {
rawType = rawType.getSuperclass();
}
return new EnumTypeAdapter(rawType);
}
};
}
public static <TT> TypeAdapterFactory newFactory(final TypeToken<TT> type, final TypeAdapter<TT> typeAdapter) {
return new TypeAdapterFactory() {
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
return typeToken.equals(type) ? typeAdapter : null;
}
};
}
public static <TT> TypeAdapterFactory newFactory(final Class<TT> type, final TypeAdapter<TT> typeAdapter) {
return new TypeAdapterFactory() {
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
return typeToken.getRawType() == type ? typeAdapter : null;
}
public String toString() {
return "Factory[type=" + type.getName() + ",adapter=" + typeAdapter + "]";
}
};
}
public static <TT> TypeAdapterFactory newFactory(final Class<TT> unboxed, final Class<TT> boxed, final TypeAdapter<? super TT> typeAdapter) {
return new TypeAdapterFactory() {
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
Class<? super T> rawType = typeToken.getRawType();
return (rawType == unboxed || rawType == boxed) ? typeAdapter : null;
}
public String toString() {
return "Factory[type=" + boxed.getName() + "+" + unboxed.getName() + ",adapter=" + typeAdapter + "]";
}
};
}
public static <TT> TypeAdapterFactory newFactoryForMultipleTypes(final Class<TT> base, final Class<? extends TT> sub, final TypeAdapter<? super TT> typeAdapter) {
return new TypeAdapterFactory() {
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
Class<? super T> rawType = typeToken.getRawType();
return (rawType == base || rawType == sub) ? typeAdapter : null;
}
public String toString() {
return "Factory[type=" + base.getName() + "+" + sub.getName() + ",adapter=" + typeAdapter + "]";
}
};
}
public static <TT> TypeAdapterFactory newTypeHierarchyFactory(final Class<TT> clazz, final TypeAdapter<TT> typeAdapter) {
return new TypeAdapterFactory() {
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
return clazz.isAssignableFrom(typeToken.getRawType()) ? typeAdapter : null;
}
public String toString() {
return "Factory[typeHierarchy=" + clazz.getName() + ",adapter=" + typeAdapter + "]";
}
};
}
public static TypeAdapterFactory factory(EncryptorProviderService encryptorProviderService) {
return new TypeAdapterFactory() {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (Categories.class.isAssignableFrom(type.getRawType())) {
return (TypeAdapter<T>) new CategoriesTypeAdapter(gson, encryptorProviderService);
}
return null;
}
};
}
public static TypeAdapterFactory factory(EncryptorProviderService encryptorProviderService) {
return new TypeAdapterFactory() {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (Transactions.class.isAssignableFrom(type.getRawType())) {
return (TypeAdapter<T>) new TransactionsTypeAdapter(gson, encryptorProviderService);
}
return null;
}
};
}
/**
* Create a new instance of Geometry type adapter factory, this is passed into the Gson
* Builder.
*
* @return a new GSON TypeAdapterFactory
* @since 4.4.0
*/
public static TypeAdapterFactory create() {
if (geometryTypeFactory == null) {
geometryTypeFactory = RuntimeTypeAdapterFactory.of(Geometry.class, "type", true)
.registerSubtype(GeometryCollection.class, "GeometryCollection")
.registerSubtype(Point.class, "Point")
.registerSubtype(MultiPoint.class, "MultiPoint")
.registerSubtype(LineString.class, "LineString")
.registerSubtype(MultiLineString.class, "MultiLineString")
.registerSubtype(Polygon.class, "Polygon")
.registerSubtype(MultiPolygon.class, "MultiPolygon");
}
return geometryTypeFactory;
}
public void testDeserializeMissingSubtype() {
TypeAdapterFactory billingAdapter = RuntimeTypeAdapterFactory.of(BillingInstrument.class)
.registerSubtype(BankTransfer.class);
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(billingAdapter)
.create();
try {
gson.fromJson("{type:'CreditCard',ownerName:'Jesse'}", BillingInstrument.class);
fail();
} catch (JsonParseException expected) {
}
}
@Provides
@Singleton
Gson provideGson(TypeAdapterFactory typeAdapterFactory) {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapterFactory(typeAdapterFactory);
// gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
return gsonBuilder.create();
}
@SuppressWarnings("unchecked")
private TypeAdapterFactory adapterFor(Class superClass, List<Class<?>> implementations, TypeInfoGenerator infoGen, MessageBundle messageBundle) {
RuntimeTypeAdapterFactory adapterFactory = RuntimeTypeAdapterFactory.of(superClass, ValueMapper.TYPE_METADATA_FIELD_NAME);
if (implementations.isEmpty()) {
return null;
}
implementations.stream()
.filter(impl -> !ClassUtils.isAbstract(impl))
.forEach(impl -> adapterFactory.registerSubtype(impl, infoGen.generateTypeName(GenericTypeReflector.annotate(impl), messageBundle)));
return adapterFactory;
}
@Override protected JolyglotGenerics jolyglot() {
return new GsonAutoValueSpeaker() {
@Override protected TypeAdapterFactory autoValueGsonTypeAdapterFactory() {
return new TypeAdapterFactory() {
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
return gson.getDelegateAdapter(this, type);
}
};
}
};
}
@Override protected Jolyglot jolyglot() {
return new GsonAutoValueSpeaker() {
@Override protected TypeAdapterFactory autoValueGsonTypeAdapterFactory() {
return new TypeAdapterFactory() {
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
return gson.getDelegateAdapter(this, type);
}
};
}
};
}
private JsonRpcMethod(String methodName, Type[] parameterTypes, Type returnType, TypeAdapterFactory returnTypeAdapterFactory,
boolean isNotification) {
if (methodName == null)
throw new NullPointerException("methodName");
this.methodName = methodName;
this.parameterTypes = parameterTypes;
this.returnType = returnType;
this.returnTypeAdapterFactory = returnTypeAdapterFactory;
this.isNotification = isNotification;
}
private static Gson createConverter() {
final GsonBuilder builder = new GsonBuilder();
final ServiceLoader<TypeAdapterFactory> serviceLoader =
ServiceLoader.load(TypeAdapterFactory.class);
serviceLoader.forEach(builder::registerTypeAdapterFactory);
return builder.create();
}
public TreeTypeAdapter(JsonSerializer<T> serializer, JsonDeserializer<T> deserializer,
Gson gson, TypeToken<T> typeToken, TypeAdapterFactory skipPast) {
this.serializer = serializer;
this.deserializer = deserializer;
this.gson = gson;
this.typeToken = typeToken;
this.skipPast = skipPast;
}