List of usage examples for com.google.gson.reflect TypeToken getType
public final Type getType()
From source file:com.hkm.disqus.api.gson.PostTypeAdapterFactory.java
License:Apache License
@Override public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) { // Return null if not a post object if (!type.getType().equals(Post.class)) { return null; }/*from w ww . j a v a 2 s. co m*/ // Get delegate final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); // Return adapter return new TypeAdapter<T>() { @Override public void write(JsonWriter out, T value) throws IOException { delegate.write(out, value); } @Override public T read(JsonReader in) throws IOException { JsonElement jsonTree = gson.fromJson(in, JsonElement.class); JsonElement forum = jsonTree.getAsJsonObject().get("forum"); JsonElement thread = jsonTree.getAsJsonObject().get("thread"); // Process the post with the delegate T post = delegate.fromJsonTree(jsonTree); // Process forum and thread if needed if (forum.isJsonObject()) { ((Post) post).forum = gson.fromJson(forum, Forum.class); } if (thread.isJsonObject()) { ((Post) post).thread = gson.fromJson(thread, Thread.class); } // Return post return post; } }; }
From source file:com.hkm.disqus.api.gson.ThreadTypeAdapterFactory.java
License:Apache License
@Override public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) { // Return null if not the thread type if (!type.getType().equals(Thread.class)) { return null; }/* w ww.ja v a 2 s. c o m*/ // Get delegate final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); // Return adapter return new TypeAdapter<T>() { @Override public void write(JsonWriter out, T value) throws IOException { delegate.write(out, value); } @Override public T read(JsonReader in) throws IOException { JsonElement jsonTree = gson.fromJson(in, JsonElement.class); JsonElement forum = jsonTree.getAsJsonObject().get("forum"); JsonElement author = jsonTree.getAsJsonObject().get("author"); JsonElement category = jsonTree.getAsJsonObject().get("category"); // Process the thread with the delegate T thread = delegate.fromJsonTree(jsonTree); // Process forum and author if needed if (forum.isJsonObject()) { ((Thread) thread).forum = gson.fromJson(forum, Forum.class); } if (author.isJsonObject()) { ((Thread) thread).author = gson.fromJson(author, User.class); } if (category.isJsonObject()) { ((Thread) thread).category = gson.fromJson(category, Category.class); } // Return thread return thread; } }; }
From source file:com.hmwg.utils.GSONUtils.java
License:Apache License
/** * {@code JSON} ??//from www . j ava2 s. co m * * @param <T> * ?? * @param json * {@code JSON} * @param token * {@code com.google.gson.reflect.TypeToken} * @param datePattern * ?? * @return {@code JSON} * @since 1.0 */ public static <T> T fromJson(String json, TypeToken<T> token, String datePattern) { if (isBlankString(json)) { return null; } GsonBuilder builder = new GsonBuilder(); if (isBlankString(datePattern)) { datePattern = DEFAULT_DATE_PATTERN; } builder.setDateFormat(datePattern); Gson gson = builder.setDateFormat("yyyy-MM-dd HH:mm:ss").create(); try { return gson.fromJson(json, token.getType()); } catch (Exception ex) { Log.i("ws", " ? " + token.getRawType().getName() + " !" + ex.getMessage()); return null; } }
From source file:com.ibm.mil.cafejava.CafeJava.java
License:Open Source License
/** * Transforms an {@code Observable} that emits a {@code WLResponse} with a valid JSON payload * into a new Observable for the targeted {@code TypeToken}. This can be done by passing the * result of this method to the {@code compose} operator of RxJava. A {@code TypeToken} is * necessary when the targeted type is a parameterized type, such as {@code List}. A variable * number of member names can be provided for accessing JSON data that is nested arbitrarily * deep inside the response payload.//www. j av a2 s . com * * @param typeToken Captures the necessary type information for the targeted parameterized * type, such as {@code List}. * @param memberNames Variable number of member names for accessing JSON data that is nested * arbitrarily deep inside the response payload. * @return {@code Transformer} that can be supplied to the {@code compose} operator of RxJava * . The input {@code Observable} must emit a {@code WLResponse} with a valid JSON payload. */ @NonNull public static <T> Transformer<WLResponse, T> serializeTo(@NonNull final TypeToken<T> typeToken, @NonNull final String... memberNames) { return transformJson(new Func1<WLResponse, T>() { @Override public T call(WLResponse wlResponse) { JsonElement element = parseNestedJson(wlResponse, memberNames); return new Gson().fromJson(element, typeToken.getType()); } }); }
From source file:com.ibm.mil.readyapps.summit.utilities.Utils.java
License:Open Source License
/** * De-serializes a properly formatted JSON string with a "result" key into a {@code Collection} * of the specified {@code TypeToken}./*from w w w . ja v a2 s .c om*/ * * @param json JSON formatted string with a top-level "result" key. * @param token The type of a parameterized {@code Collection} that the JSON will be * de-serialized to. * @param <T> * @return A {@code Collection} built from the type of {@code token} that contains the * de-serialized JSON data. */ public static <T> T mapJsonToCollection(String json, TypeToken<T> token) { return new Gson().fromJson(getRawResultObject(json), token.getType()); }
From source file:com.ibm.og.json.type.ChoiceConfigTypeAdapterFactory.java
License:Open Source License
@Override @SuppressWarnings("unchecked") public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) { final Class<T> rawType = (Class<T>) type.getRawType(); if (!ChoiceConfig.class.equals(rawType)) { return null; }/*from w w w. j a v a2 s . co m*/ final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); return new TypeAdapter<T>() { @Override public void write(final JsonWriter out, final T value) throws IOException { delegate.write(out, value); } @Override @SuppressWarnings("rawtypes") public T read(final JsonReader in) throws IOException { final Class<?> genericType = (Class<?>) ((ParameterizedType) type.getType()) .getActualTypeArguments()[0]; final TypeAdapter<JsonElement> jsonElementAdapter = gson.getAdapter(JsonElement.class); // the tree api is used here rather than the stream api so that the full object can be // inspected and we can differentiate between a ChoiceConfig<T> object or the underlying T // object itself. With the stream api there would be no way to rewind the stream once this // determination is made // // this logic allows the user to configure a choice of T in both the standard form, or // compactly if the default choice weight is sufficient e.g. // // standard form // {"choice": {fields for T object}, "weight": 1.0} <- weight is optional here // // compact form where default weight is acceptable // {fields for T object} final JsonElement element = jsonElementAdapter.read(in); if (element.isJsonObject()) { final JsonObject object = element.getAsJsonObject(); if (object.entrySet().size() <= 2 && object.has("choice")) { return delegate.fromJsonTree(element); } } return (T) new ChoiceConfig(gson.getAdapter(TypeToken.get(genericType)).fromJsonTree(element)); } }.nullSafe(); }
From source file:com.ibm.og.json.type.SelectionConfigTypeAdapterFactory.java
License:Open Source License
@Override @SuppressWarnings("unchecked") public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) { final Class<T> rawType = (Class<T>) type.getRawType(); if (!SelectionConfig.class.equals(rawType)) { return null; }// www .j a v a 2 s .com final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); return new TypeAdapter<T>() { @Override public void write(final JsonWriter out, final T value) throws IOException { delegate.write(out, value); } @Override public T read(final JsonReader in) throws IOException { final Class<?> genericType = (Class<?>) ((ParameterizedType) type.getType()) .getActualTypeArguments()[0]; final JsonElement element = gson.getAdapter(JsonElement.class).read(in); if (element.isJsonObject()) { final JsonObject object = element.getAsJsonObject(); if (object.entrySet().size() <= 2 && object.has("choices")) { return delegate.fromJsonTree(object); } else { return (T) choice(genericType, object); } } else if (element.isJsonArray()) { return (T) choiceList(genericType, element.getAsJsonArray()); } return (T) choice(genericType, element); } private <S> SelectionConfig<S> choice(final Class<S> clazz, final JsonElement element) throws IOException { final SelectionConfig<S> config = new SelectionConfig<S>(); config.choices.add(gson.getAdapter(choiceToken(clazz)).fromJsonTree(element)); return config; } private <S> SelectionConfig<S> choiceList(final Class<S> clazz, final JsonArray array) throws IOException { final SelectionConfig<S> config = new SelectionConfig<S>(); config.choices = gson.getAdapter(choiceListToken(clazz)).fromJsonTree(array); return config; } // must use guava's TypeToken implementation to create a TypeToken instance with a dynamic // type; then convert back to gson's TypeToken implementation for use in calling code. See: // https://groups.google.com/forum/#!topic/guava-discuss/HdBuiO44uaw private <S> TypeToken<ChoiceConfig<S>> choiceToken(final Class<S> clazz) { @SuppressWarnings("serial") final com.google.common.reflect.TypeToken<ChoiceConfig<S>> choiceToken = new com.google.common.reflect.TypeToken<ChoiceConfig<S>>() { }.where(new TypeParameter<S>() { }, com.google.common.reflect.TypeToken.of(clazz)); return (TypeToken<ChoiceConfig<S>>) TypeToken.get(choiceToken.getType()); } private <S> TypeToken<List<ChoiceConfig<S>>> choiceListToken(final Class<S> clazz) { @SuppressWarnings("serial") final com.google.common.reflect.TypeToken<List<ChoiceConfig<S>>> choiceToken = new com.google.common.reflect.TypeToken<List<ChoiceConfig<S>>>() { }.where(new TypeParameter<S>() { }, com.google.common.reflect.TypeToken.of(clazz)); return (TypeToken<List<ChoiceConfig<S>>>) TypeToken.get(choiceToken.getType()); } }.nullSafe(); }
From source file:com.ikanow.infinit.e.data_model.api.ApiManager.java
License:Apache License
@SuppressWarnings("unchecked") public static <S> S mapFromApi(String s, TypeToken<S> type, BasePojoApiMap<S> apiMap) { GsonBuilder gb = BaseApiPojo.getDefaultBuilder(); if (null != apiMap) { gb = apiMap.extendBuilder(gb);/*from www . j ava 2 s . co m*/ } return (S) gb.create().fromJson(s, type.getType()); }
From source file:com.ikanow.infinit.e.data_model.api.ApiManager.java
License:Apache License
@SuppressWarnings("unchecked") public static <S> S mapFromApi(JsonElement j, TypeToken<S> type, BasePojoApiMap<S> apiMap) { GsonBuilder gb = BaseApiPojo.getDefaultBuilder(); if (null != apiMap) { gb = apiMap.extendBuilder(gb);/*from w ww.j av a 2s. com*/ } return (S) gb.create().fromJson(j, type.getType()); }
From source file:com.ikanow.infinit.e.data_model.api.ApiManager.java
License:Apache License
public static <S> String mapListToApi(Collection<S> list, TypeToken<? extends Collection<S>> listType, BasePojoApiMap<S> apiMap) { GsonBuilder gb = BaseApiPojo.getDefaultBuilder(); if (null != apiMap) { gb = apiMap.extendBuilder(gb);/*from w w w .j ava 2s . c o m*/ } return gb.create().toJson(list, listType.getType()); }