Example usage for com.google.gson TypeAdapter nullSafe

List of usage examples for com.google.gson TypeAdapter nullSafe

Introduction

In this page you can find the example usage for com.google.gson TypeAdapter nullSafe.

Prototype

public final TypeAdapter<T> nullSafe() 

Source Link

Document

This wrapper method is used to make a type adapter null tolerant.

Usage

From source file:org.jclouds.json.config.GsonModule.java

License:Apache License

@SuppressWarnings("rawtypes")
@Provides/*from   w  ww  .  ja  va2  s  . co  m*/
@Singleton
Gson provideGson(TypeAdapter<JsonBall> jsonAdapter, DateAdapter adapter, ByteListAdapter byteListAdapter,
        ByteArrayAdapter byteArrayAdapter, PropertiesAdapter propertiesAdapter, JsonAdapterBindings bindings,
        CredentialsAdapterFactory credentialsAdapterFactory, OptionalTypeAdapterFactory optional,
        SetTypeAdapterFactory set, ImmutableSetTypeAdapterFactory immutableSet, MapTypeAdapterFactory map,
        MultimapTypeAdapterFactory multimap, IterableTypeAdapterFactory iterable,
        CollectionTypeAdapterFactory collection, ListTypeAdapterFactory list,
        ImmutableListTypeAdapterFactory immutableList, FluentIterableTypeAdapterFactory fluentIterable,
        ImmutableMapTypeAdapterFactory immutableMap, 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(credentialsAdapterFactory);
    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);
    builder.registerTypeAdapterFactory(immutableMap);

    AnnotationConstructorNamingStrategy deserializationPolicy = new AnnotationConstructorNamingStrategy(
            ImmutableSet.of(ConstructorProperties.class, SerializedNames.class, Inject.class),
            ImmutableSet.of(new ExtractNamed()));

    builder.registerTypeAdapterFactory(new DeserializationConstructorAndReflectiveTypeAdapterFactory(
            new ConstructorConstructor(ImmutableMap.<Type, InstanceCreator<?>>of()), 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();
}

From source file:us.blanshard.sudoku.messages.Rpc.java

License:Apache License

/**
 * Registers type adapters in the given builder so that {@link Request} and
 * {@link Response} objects can be serialized and deserialized in a symmetric
 * way.//from w  w w  .  j  a v  a  2s . c o  m
 *
 * <p>
 * The request deserializer requires the "method" field of the request to come
 * before the "params" field, which requirement is not strictly conformant
 * with JSON. The serializer ensures that they are in that order.
 *
 * <p>
 * Likewise, the response's "id" field must come before the "result" field.
 */
public static GsonBuilder register(GsonBuilder builder, final Function<String, Type> methodToParamsType,
        final Function<Integer, Type> idToResultType) {

    builder.registerTypeAdapterFactory(new TypeAdapterFactory() {

        @SuppressWarnings("unchecked")
        @Override
        public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) {
            if (type.getRawType() == Request.class) {
                TypeAdapter<Request> typeAdapter = new RequestAdapter(gson, methodToParamsType);
                return (TypeAdapter<T>) typeAdapter.nullSafe();
            }
            if (type.getRawType() == Response.class) {
                TypeAdapter<Response<Object>> typeAdapter = new ResponseAdapter(gson, idToResultType);
                return (TypeAdapter<T>) typeAdapter.nullSafe();
            }
            return null;
        }
    });

    return builder.serializeSpecialFloatingPointValues();
}