List of usage examples for com.google.gson.reflect TypeToken getRawType
public final Class<? super T> getRawType()
From source file:com.example.killnono.common.datacore.net.converter.maplist.JsonConverterFactory.java
License:Open Source License
@Override public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {// w w w .j a va2 s . c o m TypeToken<?> typeToken = TypeToken.get(type); if (typeToken.getRawType() == JSONObject.class) { return new JsonResponseBodyConverter<JSONObject>(); } else if (typeToken.getRawType() == JSONArray.class) { return new ListResponseBodyConverter<JSONArray>(); } else { try { throw new Throwable("?"); } catch (Throwable throwable) { throwable.printStackTrace(); return null; } } }
From source file:com.feed_the_beast.javacurselib.utils.BetterEnumAdapterFactory.java
License:Apache License
@Override 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; }// w ww .j av a 2s. c o m if (!rawType.isEnum()) { rawType = rawType.getSuperclass(); // handle anonymous subclasses } // We only care enums which implements BetterEnum for getValue method if (!BetterEnum.class.isAssignableFrom(rawType) || rawType == BetterEnum.class) { return null; } return (TypeAdapter<T>) new EnumTypeAdapter(rawType); }
From source file:com.flipkart.android.proteus.gson.ProteusTypeAdapterFactory.java
License:Apache License
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { Class clazz = type.getRawType(); if (clazz == Primitive.class) { //noinspection unchecked return (TypeAdapter<T>) PRIMITIVE_TYPE_ADAPTER; } else if (clazz == ObjectValue.class) { //noinspection unchecked return (TypeAdapter<T>) OBJECT_TYPE_ADAPTER; } else if (clazz == Array.class) { //noinspection unchecked return (TypeAdapter<T>) ARRAY_TYPE_ADAPTER; } else if (clazz == Null.class) { //noinspection unchecked return (TypeAdapter<T>) NULL_TYPE_ADAPTER; } else if (clazz == Layout.class) { //noinspection unchecked return (TypeAdapter<T>) LAYOUT_TYPE_ADAPTER; } else if (clazz == Value.class) { //noinspection unchecked return (TypeAdapter<T>) VALUE_TYPE_ADAPTER; }/* ww w . j a v a 2s . c o m*/ return null; }
From source file:com.flipkart.batching.gson.adapters.BatchingTypeAdapterFactory.java
License:Open Source License
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { Class<? super T> rawType = type.getRawType(); if (rawType.isAssignableFrom(JSONObject.class)) { return (TypeAdapter<T>) BatchingTypeAdapters.getJSONObjectTypeAdapter(gson); } else if (rawType.isAssignableFrom(JSONArray.class)) { return (TypeAdapter<T>) BatchingTypeAdapters.getJSONArrayTypeAdapter(gson); }//from w w w .ja va2s .c om return null; }
From source file:com.flipkart.batching.gson.RuntimeTypeAdapterFactory.java
License:Open Source License
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) { if (type.getRawType() != baseType) { return null; }/*from w w w . jav a 2s . c om*/ final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<>(); final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<>(); for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) { TypeAdapter<?> delegate = labelToTypeAdapter.get(entry.getKey()); if (delegate == null) { delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue())); } labelToDelegate.put(entry.getKey(), delegate); subtypeToDelegate.put(entry.getValue(), delegate); } return new TypeAdapter<R>() { @Override public R read(JsonReader reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if (reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); String label = null; R result = null; while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "type": label = TypeAdapters.STRING.read(reader); break; case "value": @SuppressWarnings("unchecked") // registration requires that subtype extends T TypeAdapter<R> delegate = label == null ? null : (TypeAdapter<R>) labelToDelegate.get(label); if (delegate == null) { throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label + "; did you forget to register a subtype?"); } result = delegate.read(reader); break; default: reader.skipValue(); break; } } reader.endObject(); return result; } @Override public void write(JsonWriter out, R value) throws IOException { Class<?> srcType = value.getClass(); @SuppressWarnings("unchecked") // registration requires that subtype extends T TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType); if (delegate == null) { throw new JsonParseException( "cannot serialize " + srcType.getName() + "; did you forget to register a subtype?"); } String label = subtypeToLabel.get(srcType); out.beginObject(); out.name("type"); out.value(label); out.name("value"); delegate.write(out, value); out.endObject(); } }.nullSafe(); }
From source file:com.framework.util.JSONUtil.java
License:Apache License
/** * {@code JSON} ??/*from w w w . j ava 2s . c o 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 (Tools.isEmpty(json)) { return null; } GsonBuilder builder = new GsonBuilder(); if (Tools.isEmpty(datePattern)) { datePattern = DEFAULT_DATE_PATTERN; } Gson gson = builder.create(); try { return gson.fromJson(json, token.getType()); } catch (Exception ex) { LOGGER.error(json + " ? " + token.getRawType().getName() + " !", ex); return null; } }
From source file:com.gilecode.yagson.adapters.ThreadTypesAdapterFactory.java
License:Apache License
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { Class<? super T> rawType = typeToken.getRawType(); if (ThreadGroup.class.isAssignableFrom(rawType)) { @SuppressWarnings({ "unchecked", "rawtypes" }) TypeAdapter<T> result = (TypeAdapter) new ThreadGroupAdapter(); return result; } else if (Thread.class.isAssignableFrom(rawType)) { @SuppressWarnings({ "unchecked", "rawtypes" }) TypeAdapter<T> result = (TypeAdapter) new ThreadAdapter(); return result; } else if (ThreadLocal.class.isAssignableFrom(rawType)) { TypeToken<?> fieldType = TypeToken.get($Gson$Types.getSingleParameterType(typeToken.getType(), typeToken.getRawType(), ThreadLocal.class)); ReflectiveTypeAdapterFactory.BoundField valueField = new ReflectiveTypeAdapterFactory.DefaultBoundField( "@.value", null, true, true, gson, fieldType) { @Override/*from ww w .j a v a 2 s. c o m*/ protected boolean writeField(Object value, WriteContext ctx) throws IOException, IllegalAccessException { if (value == null) { return false; } Object threadLocalMap = getCurrentThreadMap(value); return threadLocalMap != null && getThreadLocalEntry(threadLocalMap, value) != null; } @Override @SuppressWarnings("unchecked") protected void applyReadFieldValue(Object value, Object fieldValue) throws IllegalAccessException { if (fieldValue != null) { ((ThreadLocal) value).set(fieldValue); } } @Override protected Object getFieldValue(Object value) throws IllegalAccessException { Object threadLocalMap = getCurrentThreadMap(value); if (threadLocalMap != null) { Object threadLocalEntry = getThreadLocalEntry(threadLocalMap, value); if (threadLocalEntry != null) { return threadLocalEntryValueField.get(threadLocalEntry); } } return null; } @SuppressWarnings("unchecked") protected void applyReadPlaceholder(final Object value, Map<Field, ReferencePlaceholder> fieldPlaceholders, ReferencePlaceholder fieldValuePlaceholder) { // the thread local's "value" is not a real field, so do not add it to 'fieldPlaceholders' map fieldValuePlaceholder.registerUse(new PlaceholderUse() { @Override public void applyActualObject(Object actualObject) throws IOException { try { applyReadFieldValue(value, actualObject); } catch (IllegalAccessException e) { throw new IOException(e); } } }); } }; return gson.getReflectiveTypeAdapterFactory().createSpecial(gson, typeToken, Collections.singletonList(valueField), null); } return null; }
From source file:com.github.filosganga.geogson.gson.GeometryAdapterFactory.java
License:Apache License
@Override @SuppressWarnings("unchecked") public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { if (Geometry.class.isAssignableFrom(type.getRawType())) { return (TypeAdapter<T>) new GeometryAdapter(gson); } else if (Positions.class.isAssignableFrom(type.getRawType())) { return (TypeAdapter<T>) new PositionsAdapter(); } else if (Feature.class.isAssignableFrom(type.getRawType())) { return (TypeAdapter<T>) new FeatureAdapter(gson); } else if (FeatureCollection.class.isAssignableFrom(type.getRawType())) { return (TypeAdapter<T>) new FeatureCollectionAdapter(gson); } else {//from ww w . j a v a 2s. c om return null; } }
From source file:com.github.gfx.android.orma.gson.SingleAssociationTypeAdapterFactory.java
License:Apache License
@Override public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> typeToken) { if (!typeToken.getRawType().isAssignableFrom(SingleAssociation.class)) { return null; }//w w w.j a va2s . c o m if (!(typeToken.getType() instanceof ParameterizedType)) { throw new ClassCastException( "Expected a parameterized SingleAssociation<T>, but got " + typeToken.getType()); } final Class<?> modelType = (Class<?>) ((ParameterizedType) typeToken.getType()).getActualTypeArguments()[0]; final Schema<?> schema = Schemas.get(modelType); return new TypeAdapter<T>() { @Override public void write(JsonWriter out, T value) throws IOException { SingleAssociation<?> association = (SingleAssociation<?>) value; gson.toJson(association.get(), modelType, out); } @Override @SuppressWarnings("unchecked") public T read(JsonReader in) throws IOException { Object model = gson.fromJson(in, modelType); return (T) SingleAssociation.just((Schema<Object>) schema, model); } }; }
From source file:com.github.kyriosdata.regras.infraestrutura.CustomRegraTypeAdapterFactory.java
License:Creative Commons License
@Override public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) { if (type.getRawType() != Regra.class) return null; final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); return new TypeAdapter<T>() { @Override//from w w w .jav a 2 s.c o m public void write(final JsonWriter jsonWriter, final T t) throws IOException { jsonWriter.beginObject(); jsonWriter.name("tipo"); jsonWriter.value(getTipo(t.getClass().getName())); jsonWriter.name("obj"); delegate.write(jsonWriter, t); jsonWriter.endObject(); } @Override public T read(final JsonReader jsonReader) throws IOException, JsonParseException { JsonElement tree = Streams.parse(jsonReader); JsonObject object = tree.getAsJsonObject(); String clazz = object.get("tipo").getAsString(); JsonElement obj = object.get("obj").getAsJsonObject(); if ("expressao".equals(clazz)) { return (T) gson.getDelegateAdapter(CustomRegraTypeAdapterFactory.this, TypeToken.get(RegraExpressao.class)).fromJsonTree(obj); } if ("pontosPorRelato".equals(clazz)) { return (T) gson.getDelegateAdapter(CustomRegraTypeAdapterFactory.this, TypeToken.get(RegraPontosPorRelato.class)).fromJsonTree(obj); } throw new JsonParseException("Erro ao desserializar " + type + ". No uma regra?"); } }; }