Example usage for com.google.gson TypeAdapterFactory TypeAdapterFactory

List of usage examples for com.google.gson TypeAdapterFactory TypeAdapterFactory

Introduction

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

Prototype

TypeAdapterFactory

Source Link

Usage

From source file:co.cask.cdap.common.stream.StreamEventTypeAdapter.java

License:Apache License

/**
 * 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
 *///from   w  w w . j ava2 s  .  c  o m
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;
        }
    });
}

From source file:com.greensopinion.finance.services.persistence.CategoriesTypeAdapter.java

License:Apache License

public static TypeAdapterFactory factory(EncryptorProviderService encryptorProviderService) {
    return new TypeAdapterFactory() {

        @SuppressWarnings("unchecked")
        @Override//www.j  a  v  a2 s  . c o m
        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;
        }
    };
}

From source file:com.greensopinion.finance.services.persistence.TransactionsTypeAdapter.java

License:Apache License

public static TypeAdapterFactory factory(EncryptorProviderService encryptorProviderService) {
    return new TypeAdapterFactory() {

        @SuppressWarnings("unchecked")
        @Override//from w  w w .j  av a  2s . c  o m
        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;
        }
    };
}

From source file:de.micromata.genome.junittools.wicket.models.WicketTestBuilderGsonBuilder.java

License:Apache License

public static Gson getGson() {
    if (gsonBuilder == null) {
        gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapterFactory(new TypeAdapterFactory() {

            @Override//from  ww w  .j  a v  a2 s.  com
            public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
                if (type.getRawType() == Class.class) {
                    return new TypeAdapter<T>() {
                        @Override
                        public void write(JsonWriter out, T value) throws IOException {
                            out.value(((Class) value).getName());
                        }

                        @Override
                        public T read(JsonReader in) throws IOException {
                            try {
                                return (T) Class.forName(in.nextString());
                            } catch (ClassNotFoundException e) {
                                LOG.error("unable to transform " + in.nextString()
                                        + " to a reasonable class, please check this!");
                            }
                            return null;
                        }
                    };
                }
                return null;
            }
        });
    }
    return gsonBuilder.create();
}

From source file:net.oneandone.stool.configuration.adapter.ExtensionsAdapter.java

License:Apache License

public static TypeAdapterFactory factory(final ExtensionsFactory factory) {
    return new TypeAdapterFactory() {
        @SuppressWarnings("unchecked")
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
            if (type.getRawType().equals(Extensions.class)) {
                return (TypeAdapter<T>) new ExtensionsAdapter(gson, factory);
            }/*from   w  w  w  .  jav a 2 s  .c om*/
            return null;
        }
    };
}

From source file:net.segoia.event.eventbus.config.json.EventBusJsonConfigLoader.java

License:Apache License

public static EventBusJsonConfig load(Reader reader) {
    GsonBuilder gb = new GsonBuilder();

    gb.registerTypeAdapter(Condition.class, new JsonDeserializer<Condition>() {

        @Override/*from w w  w .j a  v a2s  . c o m*/
        public Condition deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            JsonObject jo = json.getAsJsonObject();
            JsonElement conditionType = jo.get("ctype");
            String ctype = null;
            if (conditionType != null) {
                ctype = conditionType.getAsString().trim();
                if ("".equals(ctype)) {
                    ctype = null;
                }
            }
            JsonDeserializer<?> deserializerForType = jsonDeserializers.get(ctype);
            if (deserializerForType == null) {
                throw new JsonParseException("No deserializer defined for condition type " + ctype);
            }
            return (Condition) deserializerForType.deserialize(json, typeOfT, context);
        }
    });

    gb.registerTypeAdapterFactory(new TypeAdapterFactory() {

        @Override
        public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
            final TypeAdapter<T> delegateAdapter = gson.getDelegateAdapter(this, type);

            TypeAdapter<T> typeAdapter = new TypeAdapter<T>() {

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

                @Override
                public T read(JsonReader in) throws IOException {
                    JsonElement value = Streams.parse(in);

                    if (value.isJsonNull()) {
                        return null;
                    }

                    if (!value.isJsonObject()) {
                        return delegateAdapter.fromJsonTree(value);
                    }
                    // System.out.println(value+" "+value.getClass());
                    JsonObject jo = value.getAsJsonObject();

                    JsonElement cnameElem = jo.remove("className");

                    if (cnameElem != null) {
                        String cname = cnameElem.getAsString();

                        try {
                            // System.out.println("using clazz " + cname);
                            return (T) gson.fromJson(value, Class.forName(cname));
                        } catch (ClassNotFoundException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            return null;
                        }
                    } else {
                        return delegateAdapter.fromJsonTree(value);
                    }
                }
            };

            return typeAdapter;

        }
    });

    final Gson gson = gb.create();

    EventBusJsonConfig ebusConfig = gson.fromJson(reader, EventBusJsonConfig.class);

    return ebusConfig;
}

From source file:org.immutables.mongo.bson4gson.GsonCodecs.java

License:Apache License

/**
 * Gson Factory which gives preference to existing adapters from {@code gson} instance. However,
 * if type is not supported it will query {@link CodecRegistry} to create one (if possible).
 *
 * <p>This allows supporting Bson types by Gson natively (eg. for {@link org.bson.types.ObjectId}).
 *
 * @param registry existing registry which will be used if type is unknown to {@code gson}.
 * @return factory which delegates to {@code registry} for unknown types.
 *///w  w  w .ja  v  a  2s. co m
public static TypeAdapterFactory delegatingTypeAdapterFactory(final CodecRegistry registry) {
    Preconditions.checkNotNull(registry, "registry");
    return new TypeAdapterFactory() {
        @Override
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
            boolean hasAdapter;
            try {
                TypeAdapter<T> adapter = gson.getDelegateAdapter(this, type);
                hasAdapter = !isReflectiveTypeAdapter(adapter);
            } catch (IllegalArgumentException e) {
                hasAdapter = false;
            }

            if (hasAdapter) {
                return null;
            }

            try {
                @SuppressWarnings("unchecked")
                Codec<T> codec = (Codec<T>) registry.get(type.getRawType());
                return typeAdapterFromCodec(codec);
            } catch (CodecConfigurationException e1) {
                return null;
            }

        }
    };
}

From source file:org.mule.runtime.extension.api.persistence.ExtensionModelJsonSerializer.java

License:Open Source License

private Gson buildGson() {
    final SerializationContext serializationContext = new SerializationContext();

    Gson gsonDelegate = gsonBuilder(serializationContext, prettyPrint).create();

    return gsonBuilder(serializationContext, prettyPrint).registerTypeAdapterFactory(new TypeAdapterFactory() {

        @Override/*from w w w.  j av a2  s .c  om*/
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
            if (ExtensionModel.class.isAssignableFrom(type.getRawType())) {
                return (TypeAdapter<T>) new ExtensionModelTypeAdapter(gsonDelegate, serializationContext);
            }

            return null;
        }
    }).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.//w w  w  .j  ava2s . 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();
}