Java Code Examples for com.google.gson.TypeAdapterFactory

The following examples show how to use com.google.gson.TypeAdapterFactory. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: arcusplatform   Author: arcus-smart-home   File: RuleConfigJsonModule.java    License: Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #2
Source Project: arcusplatform   Author: arcus-smart-home   File: RuleConfigJsonModule.java    License: Apache License 2.0 6 votes vote down vote up
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)
            ;
}
 
Example #3
Source Project: arcusplatform   Author: arcus-smart-home   File: GsonModule.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #4
Source Project: IridiumSkyblock   Author: IridiumLLC   File: EnumTypeAdapter.java    License: GNU General Public License v2.0 5 votes vote down vote up
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);
        }
    };
}
 
Example #5
Source Project: arcusplatform   Author: arcus-smart-home   File: RuleConfigJsonModule.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #6
Source Project: arcusplatform   Author: arcus-smart-home   File: ActionConfigJsonModule.java    License: Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #7
Source Project: gson   Author: google   File: RuntimeTypeAdapterFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
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) {
  }
}
 
Example #8
Source Project: gson   Author: google   File: JsonAdapterAnnotationTypeAdapterFactory.java    License: Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #9
Source Project: arcusplatform   Author: arcus-smart-home   File: GsonModule.java    License: Apache License 2.0 5 votes vote down vote up
@Provides
public GsonFactory gson(
   Set<TypeAdapterFactory> typeAdapterFactories,
   Set<TypeAdapter<?>> typeAdapters,
   Set<JsonSerializer<?>> serializers,
   Set<JsonDeserializer<?>> deserializers
) {
   return new GsonFactory(typeAdapterFactories, typeAdapters, serializers, deserializers, serializeNulls);
}
 
Example #10
Source Project: arcusplatform   Author: arcus-smart-home   File: PolymorphicTypeAdapterFactory.java    License: Apache License 2.0 5 votes vote down vote up
public ReflectiveTypeAdapter(
      Gson gson, 
      TypeAdapterFactory skipPast, 
      TypeToken<T> token
) {
   this.gson = gson;
   this.token = token;
}
 
Example #11
Source Project: arcusplatform   Author: arcus-smart-home   File: GsonFactory.java    License: Apache License 2.0 5 votes vote down vote up
public GsonFactory(
      Set<TypeAdapterFactory> typeAdapterFactories,
      Set<TypeAdapter<?>> typeAdapters,
      Set<JsonSerializer<?>> serializers,
      Set<JsonDeserializer<?>> deserializers
) {
   this(typeAdapterFactories, typeAdapters, serializers, deserializers, true);
}
 
Example #12
Source Project: arcusplatform   Author: arcus-smart-home   File: GsonFactory.java    License: Apache License 2.0 5 votes vote down vote up
public GsonFactory(
      Set<TypeAdapterFactory> typeAdapterFactories,
      Set<TypeAdapter<?>> typeAdapters,
      Set<JsonSerializer<?>> serializers,
      Set<JsonDeserializer<?>> deserializers,
      boolean serializeNulls
) {
   this.gson = create(typeAdapterFactories, typeAdapters, serializers, deserializers, serializeNulls);
}
 
Example #13
Source Project: ProjectAres   Author: OvercastNetwork   File: SerializationManifest.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@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;
}
 
Example #14
Source Project: letv   Author: JackChan1999   File: TypeAdapters.java    License: Apache License 2.0 5 votes vote down vote up
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);
        }
    };
}
 
Example #15
Source Project: letv   Author: JackChan1999   File: TypeAdapters.java    License: Apache License 2.0 5 votes vote down vote up
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;
        }
    };
}
 
Example #16
Source Project: letv   Author: JackChan1999   File: TypeAdapters.java    License: Apache License 2.0 5 votes vote down vote up
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 + "]";
        }
    };
}
 
Example #17
Source Project: letv   Author: JackChan1999   File: TypeAdapters.java    License: Apache License 2.0 5 votes vote down vote up
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 + "]";
        }
    };
}
 
Example #18
Source Project: letv   Author: JackChan1999   File: TypeAdapters.java    License: Apache License 2.0 5 votes vote down vote up
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 + "]";
        }
    };
}
 
Example #19
Source Project: letv   Author: JackChan1999   File: TypeAdapters.java    License: Apache License 2.0 5 votes vote down vote up
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 + "]";
        }
    };
}
 
Example #20
Source Project: greenbeans   Author: greensopinion   File: CategoriesTypeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
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;
		}
	};
}
 
Example #21
Source Project: greenbeans   Author: greensopinion   File: TransactionsTypeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
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;
		}
	};
}
 
Example #22
Source Project: mapbox-java   Author: mapbox   File: GeometryAdapterFactory.java    License: MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example #23
Source Project: gson   Author: google   File: RuntimeTypeAdapterFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
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) {
  }
}
 
Example #24
Source Project: octoandroid   Author: nairbspace   File: NetworkModule.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Provides
    @Singleton
    Gson provideGson(TypeAdapterFactory typeAdapterFactory) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapterFactory(typeAdapterFactory);
//        gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
        return gsonBuilder.create();
    }
 
Example #25
Source Project: graphql-spqr   Author: leangen   File: GsonValueMapperFactory.java    License: Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #26
Source Project: Jolyglot   Author: VictorAlbertos   File: GsonAutoValueSpeakerGenericsTest.java    License: Apache License 2.0 5 votes vote down vote up
@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);
        }
      };
    }
  };
}
 
Example #27
Source Project: Jolyglot   Author: VictorAlbertos   File: GsonAutoValueSpeakerTest.java    License: Apache License 2.0 5 votes vote down vote up
@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);
        }
      };
    }
  };
}
 
Example #28
Source Project: lsp4j   Author: eclipse   File: JsonRpcMethod.java    License: Eclipse Public License 2.0 5 votes vote down vote up
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;
}
 
Example #29
Source Project: yandex-translate-api   Author: vbauer   File: DataConverterImpl.java    License: MIT License 5 votes vote down vote up
private static Gson createConverter() {
    final GsonBuilder builder = new GsonBuilder();
    final ServiceLoader<TypeAdapterFactory> serviceLoader =
        ServiceLoader.load(TypeAdapterFactory.class);

    serviceLoader.forEach(builder::registerTypeAdapterFactory);

    return builder.create();
}
 
Example #30
Source Project: gson   Author: google   File: TreeTypeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
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;
}