Java Examples for com.google.gson.TypeAdapterFactory

The following java examples will help you to understand the usage of com.google.gson.TypeAdapterFactory. These source code samples are taken from different open source projects.

Example 1
Project: ProjectAres-master  File: SerializationManifest.java View source code
@Provides
GsonBuilder gsonBuilder(Set<TypeAdapterFactory> factories, Map<Type, Object> adapters, Map<Class, Object> hiearchyAdapters) {
    GsonBuilder builder = new GsonBuilder().setDateFormat(ISO8601_DATE_FORMAT).serializeSpecialFloatingPointValues().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 2
Project: CanZE-master  File: TypeAdapters.java View source code
public static <TT> TypeAdapterFactory newFactory(final TypeToken<TT> type, final TypeAdapter<TT> typeAdapter) {
    return new TypeAdapterFactory() {

        // we use a runtime check to make sure the 'T's equal
        @SuppressWarnings("unchecked")
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
            return typeToken.equals(type) ? (TypeAdapter<T>) typeAdapter : null;
        }
    };
}
Example 3
Project: SkinsRestorer-master  File: TypeAdapters.java View source code
public static <TT> TypeAdapterFactory newFactory(final TypeToken<TT> type, final TypeAdapter<TT> typeAdapter) {
    return new TypeAdapterFactory() {

        // we use a runtime check to make sure the 'T's equal
        @SuppressWarnings("unchecked")
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
            return typeToken.equals(type) ? (TypeAdapter<T>) typeAdapter : null;
        }
    };
}
Example 4
Project: TWRadiationAndroid-master  File: TypeAdapters.java View source code
public static <TT> TypeAdapterFactory newFactory(final TypeToken<TT> type, final TypeAdapter<TT> typeAdapter) {
    return new TypeAdapterFactory() {

        // we use a runtime check to make sure the 'T's equal
        @SuppressWarnings("unchecked")
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
            return typeToken.equals(type) ? (TypeAdapter<T>) typeAdapter : null;
        }
    };
}
Example 5
Project: datakernel-master  File: Utils.java View source code
static GsonBuilder createGsonBuilder(final Map<String, Type> attributeTypes, final Map<String, Type> measureTypes) {
    return new GsonBuilder().serializeNulls().registerTypeAdapterFactory(new TypeAdapterFactory() {

        @SuppressWarnings("unchecked")
        @Override
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
            if (AggregationPredicate.class.isAssignableFrom(type.getRawType())) {
                return (TypeAdapter<T>) AggregationPredicateGsonAdapter.create(gson, attributeTypes, measureTypes);
            }
            if (type.getRawType() == QueryResult.class) {
                return (TypeAdapter<T>) QueryResultGsonAdapter.create(gson, attributeTypes, measureTypes);
            }
            return null;
        }
    }).registerTypeAdapter(LocalDate.class, new TypeAdapter<LocalDate>() {

        @Override
        public void write(JsonWriter out, LocalDate value) throws IOException {
            out.value(value.toString());
        }

        @Override
        public LocalDate read(JsonReader in) throws IOException {
            return LocalDate.parse(in.nextString());
        }
    }).registerTypeAdapter(CubeQuery.Ordering.class, QueryOrderingGsonAdapter.create());
}
Example 6
Project: cdap-master  File: StreamEventTypeAdapter.java View source code
/**
   * Register an instance of the {@link StreamEventTypeAdapter} to the given {@link GsonBuilder}.
   * @param gsonBuilder The build to register to
   * @return The same {@link GsonBuilder} instance in the argument
   */
public static GsonBuilder register(GsonBuilder gsonBuilder) {
    return gsonBuilder.registerTypeAdapterFactory(new TypeAdapterFactory() {

        @Override
        @SuppressWarnings("unchecked")
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
            if (StreamEvent.class.isAssignableFrom(type.getRawType())) {
                return (TypeAdapter<T>) new StreamEventTypeAdapter(gson.getAdapter(HEADERS_TYPE));
            }
            return null;
        }
    });
}
Example 7
Project: apmrouter-master  File: GSONJSONMarshaller.java View source code
/**
	 * Creates a new Gson instance based on the settings in this bean.
	 */
protected void update() {
    GsonBuilder builder = new GsonBuilder();
    if (prettyPrint)
        builder.setPrettyPrinting();
    if (disableHtmlEscaping)
        builder.disableHtmlEscaping();
    if (!adapterInstances.isEmpty()) {
        for (Map.Entry<Type, Object> entry : adapterInstances.entrySet()) {
            builder.registerTypeAdapter(entry.getKey(), entry.getValue());
        }
    }
    if (!adapterFactoryInstances.isEmpty()) {
        for (TypeAdapterFactory taf : adapterFactoryInstances) {
            builder.registerTypeAdapterFactory(taf);
        }
    }
    gson = builder.create();
}
Example 8
Project: ElementalArrows-master  File: GsonParser.java View source code
private Gson bake() throws Exception {
    if (this.gson != null) {
        return this.gson;
    }
    this.gson = this.builder.create();
    // Some tricky stuff is happening here... We replace the @Fields with
    // a SerializedType provider to use the serialized type provided by the
    // provider. Gson doesn't provide a method to do this easily.
    java.lang.reflect.Field field = Gson.class.getDeclaredField("factories");
    field.setAccessible(true);
    // Get the factories of the gson
    //noinspection unchecked
    List<TypeAdapterFactory> factories = (List<TypeAdapterFactory>) field.get(this.gson);
    // The reflective factory is at the last index
    final ReflectiveTypeAdapterFactory factory = (ReflectiveTypeAdapterFactory) factories.get(factories.size() - 1);
    // The factories is modifiable, lets fix that
    if (factories instanceof RandomAccess) {
        field = factories.getClass().getSuperclass().getDeclaredField("list");
    } else {
        field = factories.getClass().getDeclaredField("list");
    }
    field.setAccessible(true);
    //noinspection unchecked
    factories = (List<TypeAdapterFactory>) field.get(factories);
    // Replace the default type adapter factory
    factories.set(factories.size() - 1, new TypeAdapterFactory() {

        @Nullable
        @Override
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
            final TypeAdapter adapter = factory.create(gson, (TypeToken) typeToken);
            if (adapter == null) {
                return null;
            }
            try {
                final java.lang.reflect.Field field1 = ReflectiveTypeAdapterFactory.Adapter.class.getDeclaredField("boundFields");
                field1.setAccessible(true);
                // Get the bound fields
                //noinspection unchecked
                final Map<String, Object> boundFields = (Map<String, Object>) field1.get(adapter);
                Class<?> raw = typeToken.getRawType();
                while (raw != Object.class && raw != null) {
                    final java.lang.reflect.Field[] fields = raw.getDeclaredFields();
                    for (final java.lang.reflect.Field field2 : fields) {
                        field2.setAccessible(true);
                        if (field2.getAnnotation(Field.class) == null) {
                            continue;
                        }
                        final String name = field2.getName();
                        if (boundFields.containsKey(name)) {
                            final SerializedType serializedType = field2.getAnnotation(SerializedType.class);
                            if (serializedType != null) {
                                final Constructor constructor = serializedType.value().getDeclaredConstructor();
                                constructor.setAccessible(true);
                                final SerializedTypeProvider provider = (SerializedTypeProvider) constructor.newInstance();
                                final Object boundField = boundFields.get(name);
                                boundFields.put(name, new LanternReflectiveBoundField(boundField) {

                                    @Override
                                    protected void write(JsonWriter writer, Object value) throws IOException, IllegalAccessException {
                                        final Object fieldValue = field2.get(value);
                                        //noinspection unchecked
                                        final TypeToken<?> type = provider.get(name, value);
                                        final TypeAdapter typeAdapter = gson.getAdapter(type);
                                        final TypeAdapter typeAdapterWrapper = LanternTypeAdapterRuntimeTypeWrapper.create(gson, typeAdapter, type.getType());
                                        //noinspection unchecked
                                        typeAdapterWrapper.write(writer, fieldValue);
                                    }

                                    @Override
                                    protected void read(JsonReader reader, Object value) throws IOException, IllegalAccessException {
                                        //noinspection unchecked
                                        final TypeToken<?> type = provider.get(name, value);
                                        final TypeAdapter typeAdapter = gson.getAdapter(type);
                                        final Object fieldValue = typeAdapter.read(reader);
                                        if (fieldValue != null) {
                                            field2.set(value, fieldValue);
                                        }
                                    }
                                });
                            }
                        }
                    }
                    raw = raw.getSuperclass();
                }
            } catch (Exception e) {
                throw Throwables.propagate(e);
            }
            //noinspection unchecked
            return adapter;
        }
    });
    return this.gson;
}
Example 9
Project: legacy-jclouds-master  File: GsonModule.java View source code
@SuppressWarnings("rawtypes")
@Provides
@Singleton
Gson provideGson(TypeAdapter<JsonBall> jsonAdapter, DateAdapter adapter, ByteListAdapter byteListAdapter, ByteArrayAdapter byteArrayAdapter, PropertiesAdapter propertiesAdapter, JsonAdapterBindings bindings, OptionalTypeAdapterFactory optional, SetTypeAdapterFactory set, ImmutableSetTypeAdapterFactory immutableSet, MapTypeAdapterFactory map, MultimapTypeAdapterFactory multimap, IterableTypeAdapterFactory iterable, CollectionTypeAdapterFactory collection, ListTypeAdapterFactory list, ImmutableListTypeAdapterFactory immutableList, FluentIterableTypeAdapterFactory fluentIterable, DefaultExclusionStrategy exclusionStrategy) {
    FieldNamingStrategy serializationPolicy = new AnnotationOrNameFieldNamingStrategy(ImmutableSet.of(new ExtractSerializedName(), new ExtractNamed()));
    GsonBuilder builder = new GsonBuilder().setFieldNamingStrategy(serializationPolicy).setExclusionStrategies(exclusionStrategy);
    // simple (type adapters)
    builder.registerTypeAdapter(Properties.class, propertiesAdapter.nullSafe());
    builder.registerTypeAdapter(Date.class, adapter.nullSafe());
    builder.registerTypeAdapter(byte[].class, byteArrayAdapter.nullSafe());
    builder.registerTypeAdapter(JsonBall.class, jsonAdapter.nullSafe());
    builder.registerTypeAdapterFactory(optional);
    builder.registerTypeAdapterFactory(iterable);
    builder.registerTypeAdapterFactory(collection);
    builder.registerTypeAdapterFactory(list);
    builder.registerTypeAdapter(new TypeToken<List<Byte>>() {
    }.getType(), byteListAdapter.nullSafe());
    builder.registerTypeAdapterFactory(immutableList);
    builder.registerTypeAdapterFactory(set);
    builder.registerTypeAdapterFactory(immutableSet);
    builder.registerTypeAdapterFactory(map);
    builder.registerTypeAdapterFactory(multimap);
    builder.registerTypeAdapterFactory(fluentIterable);
    AnnotationConstructorNamingStrategy deserializationPolicy = new AnnotationConstructorNamingStrategy(ImmutableSet.of(ConstructorProperties.class, Inject.class), ImmutableSet.of(new ExtractNamed()));
    builder.registerTypeAdapterFactory(new DeserializationConstructorAndReflectiveTypeAdapterFactory(new ConstructorConstructor(), serializationPolicy, Excluder.DEFAULT, deserializationPolicy));
    // complicated (serializers/deserializers as they need context to operate)
    builder.registerTypeHierarchyAdapter(Enum.class, new EnumTypeAdapterThatReturnsFromValue());
    for (Map.Entry<Type, Object> binding : bindings.getBindings().entrySet()) {
        builder.registerTypeAdapter(binding.getKey(), binding.getValue());
    }
    for (TypeAdapterFactory factory : bindings.getFactories()) {
        builder.registerTypeAdapterFactory(factory);
    }
    return builder.create();
}
Example 10
Project: jclouds-master  File: JsonTest.java View source code
public void autoValueSerializedNames_overriddenTypeAdapterFactory() {
    Json json = Guice.createInjector(new GsonModule(), new AbstractModule() {

        @Override
        protected void configure() {
        }

        @Provides
        public Set<TypeAdapterFactory> typeAdapterFactories() {
            return ImmutableSet.<TypeAdapterFactory>of(new NestedSerializedNamesTypeAdapterFactory());
        }
    }).getInstance(Json.class);
    assertEquals(json.toJson(nested), "{\"id\":\"1234\",\"count\":1}");
    assertEquals(json.fromJson("{\"id\":\"1234\",\"count\":1}", NestedSerializedNamesType.class), nested);
}
Example 11
Project: funf-core-android-master  File: Probe.java View source code
protected GsonBuilder getGsonBuilder() {
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapterFactory(FunfManager.getProbeFactory(getContext()));
    TypeAdapterFactory adapterFactory = getSerializationFactory();
    if (adapterFactory != null) {
        builder.registerTypeAdapterFactory(adapterFactory);
    }
    builder.registerTypeAdapterFactory(BundleTypeAdapter.FACTORY);
    return builder;
}
Example 12
Project: funf-v4-master  File: Probe.java View source code
protected GsonBuilder getGsonBuilder() {
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapterFactory(FunfManager.getProbeFactory(getContext()));
    TypeAdapterFactory adapterFactory = getSerializationFactory();
    if (adapterFactory != null) {
        builder.registerTypeAdapterFactory(adapterFactory);
    }
    builder.registerTypeAdapterFactory(BundleTypeAdapter.FACTORY);
    return builder;
}
Example 13
Project: newFunf-master  File: TypeAdapters.java View source code
public static <TT> TypeAdapterFactory newEnumTypeHierarchyFactory() {
    return new TypeAdapterFactory() {

        @SuppressWarnings({ "rawtypes", "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()) {
                // handle anonymous subclasses
                rawType = rawType.getSuperclass();
            }
            return (TypeAdapter<T>) new EnumTypeAdapter(rawType);
        }
    };
}
Example 14
Project: AllArkhamPlugins-master  File: TypeAdapters.java View source code
public static TypeAdapterFactory newEnumTypeHierarchyFactory() {
    return new TypeAdapterFactory() {

        @SuppressWarnings({ "rawtypes", "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()) {
                // handle anonymous subclasses
                rawType = rawType.getSuperclass();
            }
            return (TypeAdapter<T>) new EnumTypeAdapter(rawType);
        }
    };
}
Example 15
Project: andbase-master  File: TypeAdapters.java View source code
public static <TT> TypeAdapterFactory newEnumTypeHierarchyFactory() {
    return new TypeAdapterFactory() {

        @SuppressWarnings({ "rawtypes", "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()) {
                // handle anonymous subclasses
                rawType = rawType.getSuperclass();
            }
            return (TypeAdapter<T>) new EnumTypeAdapter(rawType);
        }
    };
}
Example 16
Project: andbase2x-master  File: TypeAdapters.java View source code
public static <TT> TypeAdapterFactory newEnumTypeHierarchyFactory() {
    return new TypeAdapterFactory() {

        @SuppressWarnings({ "rawtypes", "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()) {
                // handle anonymous subclasses
                rawType = rawType.getSuperclass();
            }
            return (TypeAdapter<T>) new EnumTypeAdapter(rawType);
        }
    };
}
Example 17
Project: android-http-lib-based-on-volley-master  File: TypeAdapters.java View source code
public static TypeAdapterFactory newEnumTypeHierarchyFactory() {
    return new TypeAdapterFactory() {

        @SuppressWarnings({ "rawtypes", "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()) {
                // handle anonymous subclasses
                rawType = rawType.getSuperclass();
            }
            return (TypeAdapter<T>) new EnumTypeAdapter(rawType);
        }
    };
}
Example 18
Project: BitTorrentApp-master  File: TypeAdapters.java View source code
public static TypeAdapterFactory newEnumTypeHierarchyFactory() {
    return new TypeAdapterFactory() {

        @SuppressWarnings({ "rawtypes", "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()) {
                // handle anonymous subclasses
                rawType = rawType.getSuperclass();
            }
            return (TypeAdapter<T>) new EnumTypeAdapter(rawType);
        }
    };
}
Example 19
Project: commonJar-master  File: TypeAdapters.java View source code
public static TypeAdapterFactory newEnumTypeHierarchyFactory() {
    return new TypeAdapterFactory() {

        @Override
        @SuppressWarnings({ "rawtypes", "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()) {
                // handle anonymous subclasses
                rawType = rawType.getSuperclass();
            }
            return new EnumTypeAdapter(rawType);
        }
    };
}
Example 20
Project: Edge-Node-master  File: TypeAdapters.java View source code
public static TypeAdapterFactory newEnumTypeHierarchyFactory() {
    return new TypeAdapterFactory() {

        @SuppressWarnings({ "rawtypes", "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()) {
                // handle anonymous subclasses
                rawType = rawType.getSuperclass();
            }
            return (TypeAdapter<T>) new EnumTypeAdapter(rawType);
        }
    };
}
Example 21
Project: OpenChat-master  File: GsonAutoValueTypeAdapterFactory.java View source code
public static TypeAdapterFactory create() {
    return new AutoValueGson_GsonAutoValueTypeAdapterFactory();
}
Example 22
Project: photogallery-master  File: EntityTypeAdapterFactory.java View source code
public static TypeAdapterFactory create() {
    return new AutoValueGson_EntityTypeAdapterFactory();
}
Example 23
Project: qualitymatters-master  File: EntityTypeAdapterFactory.java View source code
public static TypeAdapterFactory create() {
    return new AutoValueGson_EntityTypeAdapterFactory();
}
Example 24
Project: wheelmap-android-master  File: AutoValueAdapterFactory.java View source code
// Static factory method to access the package
// private generated implementation
public static TypeAdapterFactory create() {
    return new AutoValueGson_AutoValueAdapterFactory();
}
Example 25
Project: IMM-master  File: MongoContext.java View source code
private static com.google.gson.Gson createGson() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    for (TypeAdapterFactory factory : ServiceLoader.load(TypeAdapterFactory.class)) {
        gsonBuilder.registerTypeAdapterFactory(factory);
    }
    return gsonBuilder.create();
}
Example 26
Project: MOE-master  File: MoeTypeAdapterFactory.java View source code
public static TypeAdapterFactory create() {
    return new AutoValueGson_MoeTypeAdapterFactory();
}
Example 27
Project: caliper-master  File: GsonModule.java View source code
@Provides
@IntoSet
static TypeAdapterFactory provideTypeAdapterFactoryForInstant(InstantTypeAdapter typeAdapter) {
    return TypeAdapters.newFactory(Instant.class, typeAdapter);
}
Example 28
Project: immutables-master  File: ManualStorage.java View source code
private static Gson createGson() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    for (TypeAdapterFactory factory : ServiceLoader.load(TypeAdapterFactory.class)) {
        gsonBuilder.registerTypeAdapterFactory(factory);
    }
    return gsonBuilder.create();
}
Example 29
Project: auto-matter-master  File: AutoMatterTypeAdapter.java View source code
static <T> AutoMatterTypeAdapter<T> createForValue(final Gson gson, final TypeAdapterFactory skipFactory, final TypeToken<T> type, final Map<String, List<String>> serializedNameMethods) {
    return new AutoMatterTypeAdapter<>(gson, gson.getDelegateAdapter(skipFactory, type), serializedNameMethods);
}
Example 30
Project: molgenis-master  File: GsonFactoryBean.java View source code
public void registerTypeAdapterFactory(TypeAdapterFactory typeAdapterFactory) {
    if (typeAdapterFactoryList == null)
        typeAdapterFactoryList = new ArrayList<TypeAdapterFactory>();
    typeAdapterFactoryList.add(typeAdapterFactory);
}
Example 31
Project: GenPackage-master  File: GsonGen.java View source code
public <T> TypeAdapter<T> getDelegateAdapter(TypeAdapterFactory skipPast, TypeToken<T> type) {
    return gson.getDelegateAdapter(skipPast, type);
}
Example 32
Project: MiBandDecompiled-master  File: TypeAdapters.java View source code
public static TypeAdapterFactory newEnumTypeHierarchyFactory() {
    return new G();
}
Example 33
Project: NewCommands-master  File: JsonUtilities.java View source code
public Builder registerTypeAdapterFactory(final TypeAdapterFactory factory) {
    this.gson.registerTypeAdapterFactory(factory);
    return this;
}