@Test public void customDecoder() throws Exception { GsonDecoder decoder = new GsonDecoder(Arrays.<TypeAdapter<?>>asList(upperZone)); List<Zone> zones = new LinkedList<Zone>(); zones.add(new Zone("DENOMINATOR.IO.")); zones.add(new Zone("DENOMINATOR.IO.", "ABCD")); Response response = Response.builder() .status(200) .reason("OK") .headers(Collections.<String, Collection<String>>emptyMap()) .body(zonesJson, UTF_8) .build(); assertEquals(zones, decoder.decode(response, new TypeToken<List<Zone>>() { }.getType())); }
@SuppressWarnings("unchecked") public static <T extends Comparable<? super T>> Range<Comparable<Object>> writable(TypeAdapter<T> adapter, Range<T> range) { if (range.hasLowerBound() && range.hasUpperBound()) { return Range.range( (Comparable<Object>) writable(adapter, range.lowerEndpoint()), range.lowerBoundType(), (Comparable<Object>) writable(adapter, range.upperEndpoint()), range.upperBoundType()); } else if (range.hasLowerBound()) { return Range.downTo( (Comparable<Object>) writable(adapter, range.lowerEndpoint()), range.lowerBoundType()); } else if (range.hasUpperBound()) { return Range.upTo( (Comparable<Object>) writable(adapter, range.upperEndpoint()), range.upperBoundType()); } throw new AssertionError(); }
@SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { if (typeToken.getRawType() != Timestamp.class) { return null; } final TypeAdapter<Date> dateTypeAdapter = gson.getAdapter(Date.class); return (TypeAdapter<T>) new TypeAdapter<Timestamp>() { @Override public Timestamp read(JsonReader in) throws IOException { Date date = dateTypeAdapter.read(in); return date != null ? new Timestamp(date.getTime()) : null; } @Override public void write(JsonWriter out, Timestamp value) throws IOException { dateTypeAdapter.write(out, value); } }; }
@SuppressWarnings("unchecked") // Casts guarded by conditionals. static TypeAdapter<?> getTypeAdapter(ConstructorConstructor constructorConstructor, Gson gson, TypeToken<?> fieldType, JsonAdapter annotation) { Class<?> value = annotation.value(); if (TypeAdapter.class.isAssignableFrom(value)) { Class<TypeAdapter<?>> typeAdapter = (Class<TypeAdapter<?>>) value; return constructorConstructor.get(TypeToken.get(typeAdapter)).construct(); } if (TypeAdapterFactory.class.isAssignableFrom(value)) { Class<TypeAdapterFactory> typeAdapterFactory = (Class<TypeAdapterFactory>) value; return constructorConstructor.get(TypeToken.get(typeAdapterFactory)) .construct() .create(gson, fieldType); } throw new IllegalArgumentException( "@JsonAdapter value must be TypeAdapter or TypeAdapterFactory reference."); }
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { Class<?> rawType = type.getRawType(); TypeAdapter<Map> mapAdapter = gson.getAdapter(Map.class); TypeAdapter<Collection> collectionAdapter = gson.getAdapter(Collection.class); if (Location.class.isAssignableFrom(rawType)) { return (TypeAdapter<T>) new LocationTypeAdapter(); } else if (ConfigurationSerializable.class.isAssignableFrom(rawType)) { return (TypeAdapter<T>) new ConfigurationSerializableAdapter(mapAdapter); } else if (GUISignature.class.isAssignableFrom(rawType)) { return (TypeAdapter<T>) new GUISignatureTypeAdapter(mapAdapter, collectionAdapter); } else if (MaterialAndData.class.isAssignableFrom(rawType)) { return (TypeAdapter<T>) new MaterialAndDataAdapter(); } return null; }
@Test public void assertRegisterTypeAdapter() { Gson beforeRegisterGson = GsonFactory.getGson(); GsonFactory.registerTypeAdapter(GsonFactoryTest.class, new TypeAdapter() { @Override public Object read(final JsonReader in) throws IOException { return null; } @Override public void write(final JsonWriter out, final Object value) throws IOException { out.jsonValue("test"); } }); assertThat(beforeRegisterGson.toJson(new GsonFactoryTest()), is("{}")); assertThat(GsonFactory.getGson().toJson(new GsonFactoryTest()), is("test")); }
@SuppressWarnings("unchecked") @Override public void write(JsonWriter out, Object value) throws IOException { if (value == null) { out.nullValue(); return; } TypeAdapter<Object> typeAdapter = (TypeAdapter<Object>) gson.getAdapter(value.getClass()); if (typeAdapter instanceof ObjectTypeAdapter) { out.beginObject(); out.endObject(); return; } typeAdapter.write(out, value); }
@Override public void gatherParsers(GsonBuilder builder) { builder.registerTypeHierarchyAdapter(TrickType.class, new TypeAdapter<TrickType>() { @Override public TrickType read(JsonReader in) throws IOException { TrickType type = TrickType.byId.get(in.nextString()); if (type == null) { return TrickType.STRING; } return type; } @Override public void write(JsonWriter out, TrickType value) throws IOException { out.value(value.getId()); } }); }
public static <TT> TypeAdapterFactory newFactory( final Class<TT> unboxed, final Class<TT> boxed, final TypeAdapter<? super TT> typeAdapter) { return new TypeAdapterFactory() { @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { Class<? super T> rawType = typeToken.getRawType(); return (rawType == unboxed || rawType == boxed) ? (TypeAdapter<T>) typeAdapter : null; } @Override public String toString() { return "Factory[type=" + boxed.getName() + "+" + unboxed.getName() + ",adapter=" + typeAdapter + "]"; } }; }
private TypeAdapter<?> getFieldAdapter(Gson gson, Field field, TypeToken<?> fieldType) { JsonAdapter annotation = (JsonAdapter) field.getAnnotation(JsonAdapter.class); if (annotation != null) { TypeAdapter<?> adapter = JsonAdapterAnnotationTypeAdapterFactory.getTypeAdapter(this .constructorConstructor, gson, fieldType, annotation); if (adapter != null) { return adapter; } } return gson.getAdapter((TypeToken) fieldType); }
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { if (type.getRawType() == Object.class) { return (TypeAdapter<T>) new NumberPredictObjectTypeAdapter(gson); } return null; }
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { Type type = typeToken.getType(); Class<? super T> rawType = typeToken.getRawType(); if (!Collection.class.isAssignableFrom(rawType)) { return null; } Type elementType = C$Gson$Types.getCollectionElementType(type, rawType); return new Adapter(gson, elementType, gson.getAdapter(TypeToken.get(elementType)), this .constructorConstructor.get(typeToken)); }
public static <TT> TypeAdapterFactory newFactoryForMultipleTypes(final Class<TT> base, final Class<? extends TT> sub, final TypeAdapter<? super TT> typeAdapter) { return new TypeAdapterFactory() { @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { Class<? super T> rawType = typeToken.getRawType(); return (rawType == base || rawType == sub) ? (TypeAdapter<T>) typeAdapter : null; } @Override public String toString() { return "Factory[type=" + base.getName() + "+" + sub.getName() + ",adapter=" + typeAdapter + "]"; } }; }
private <T> TypeAdapter<T> mutationSetAdapter(TypeAdapter<T> delegate) { return new TypeAdapter<T>() { public void write(JsonWriter out, T value) throws IOException { delegate.write(out, value); } @SuppressWarnings("unchecked") public T read(JsonReader reader) throws IOException { final TypeAdapter<ArrayList<Mutation>> arrayListAdapter = gson.getAdapter(new TypeToken<ArrayList<Mutation>>(){}); return (T) new MutationSet(arrayListAdapter.read(reader)); } }; }
private List<TypeAdapter<? extends T>> lookupAdapters() { List<TypeAdapter<? extends T>> adapters = new ArrayList<>(subtypes.length); for (TypeToken<? extends T> subtype : subtypes) { adapters.add(gson.getAdapter(subtype)); } return adapters; }
@Override @SuppressWarnings("unchecked") public final <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type){ Class<T> rawType = (Class<T>)type.getRawType(); boolean hasOptionals = Arrays.stream(rawType.getDeclaredFields()) .filter(field -> !Modifier.isStatic(field.getModifiers())) .anyMatch(field -> field.getType() == Optional.class); return hasOptionals ? (TypeAdapter<T>)getClassAdapter(gson, type) : null; }
private TypeAdapter<?> getFieldAdapter(Gson gson, Field field, TypeToken<?> fieldType) { JsonAdapter annotation = field.getAnnotation(JsonAdapter.class); if (annotation != null) { TypeAdapter<?> adapter = getTypeAdapter(constructorConstructor, gson, fieldType, annotation); if (adapter != null) return adapter; } return gson.getAdapter(fieldType); }
public Adapter(Gson context, Type elementType, TypeAdapter<E> elementTypeAdapter, ObjectConstructor<? extends Collection<E>> constructor) { this.elementTypeAdapter = new TypeAdapterRuntimeTypeWrapper<E>(context, elementTypeAdapter, elementType); this.constructor = constructor; }
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { Type type = typeToken.getType(); if (!Map.class.isAssignableFrom(typeToken.getRawType())) { return null; } Type[] keyAndValueTypes = C$Gson$Types.getMapKeyAndValueTypes(type, C$Gson$Types .getRawType(type)); return new Adapter(gson, keyAndValueTypes[0], getKeyAdapter(gson, keyAndValueTypes[0]), keyAndValueTypes[1], gson.getAdapter(TypeToken.get(keyAndValueTypes[1])), this .constructorConstructor.get(typeToken)); }
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { Class<? super T> clazz = type.getRawType(); // also checks if the class can be casted to GsonSerializable Method deserializeMethod = GsonSerializable.getDeserializeMethod(clazz); if (deserializeMethod == null) { return null; } TypeAdapter<? extends GsonSerializable> typeAdapter = new TypeAdapter<GsonSerializable>() { @Override public void write(JsonWriter out, GsonSerializable value) { gson.toJson(value.serialize(), out); } @Override public GsonSerializable read(JsonReader in) throws IOException { JsonElement element = gson.fromJson(in, JsonElement.class); try { //noinspection unchecked return (GsonSerializable) deserializeMethod.invoke(null, element); } catch (Exception e) { throw new IOException(e); } } }; //noinspection unchecked return (TypeAdapter<T>) typeAdapter; }
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { Class<? super T> clazz = type.getRawType(); if (!ConfigurationSerializable.class.isAssignableFrom(clazz)) { return null; } //noinspection unchecked return (TypeAdapter<T>) new Adapter(gson); }
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); Type classType = type.getType(); if (classType == MutationSet.class) { return mutationSetAdapter(delegate); } else if (classType == GenePosition.class) { return genePositionAdapter(delegate); } return delegate; }
public static <TT> TypeAdapterFactory newTypeHierarchyFactory( final Class<TT> clazz, final TypeAdapter<TT> typeAdapter) { return new TypeAdapterFactory() { @SuppressWarnings("unchecked") public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { return clazz.isAssignableFrom(typeToken.getRawType()) ? (TypeAdapter<T>) typeAdapter : null; } @Override public String toString() { return "Factory[typeHierarchy=" + clazz.getName() + ",adapter=" + typeAdapter + "]"; } }; }
private static <T> JsonElement toJsonTree(TypeAdapter<T> typeAdapter, T value) { try { JsonTreeWriter jsonWriter = new JsonTreeWriter(); jsonWriter.setLenient(true); typeAdapter.write(jsonWriter, value); return jsonWriter.get(); } catch (Throwable e) { throw new JsonIOException(e); } }
@Override public void write( final JsonWriter out, final T value ) throws IOException { // support null objects if (value == null) { out.nullValue(); return; } // assert begin of object out.beginObject(); // get discriminator Object discriminator = fieldAccess.get(value, DISCRIMINATOR_FIELD_NAME); // write discriminator out.name(DISCRIMINATOR_FIELD_NAME); ((TypeAdapter<Object>) discriminatorTypeAdapter).write(out, discriminator); // get corresponding union field info UnionMemberInfo unionMemberInfo = memberInfoMap.get(discriminator.toString()); // write field out.name(unionMemberInfo.fieldName); ((TypeAdapter<Object>) unionMemberInfo.typeAdapter).write( out, fieldAccess.get(value, unionMemberInfo.fieldName) ); // assert end of object out.endObject(); }
@Override public <T> TypeAdapter<T> create( final Gson gson, final TypeToken<T> type ) { if (!Enum.class.isAssignableFrom(type.getRawType())) { return null; } return (TypeAdapter<T>) new EnumTypeAdapter(type.getRawType()); }
@SuppressWarnings("unchecked") @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { if (!FilterChainStep.class.isAssignableFrom(type.getRawType())) { return null; } return (TypeAdapter<T>) new FilterChainStepTypeAdapter(); }
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { Class<T> rawType = (Class<T>) type.getRawType(); if (rawType != String.class) { return null; } return (TypeAdapter<T>) new StringAdapter(); }
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { Type type = typeToken.getType(); Class<? super T> rawType = typeToken.getRawType(); if (!Collection.class.isAssignableFrom(rawType)) { return null; } Type elementType = C$Gson$Types.getCollectionElementType(type, rawType); return new Adapter(gson, elementType, gson.getAdapter(TypeToken.get(elementType)), this.constructorConstructor.getConstructor(typeToken)); }
public Adapter(Gson context, Type keyType, TypeAdapter<K> keyTypeAdapter, Type valueType, TypeAdapter<V> valueTypeAdapter, ObjectConstructor<? extends Map<K, V>> constructor) { this.keyTypeAdapter = new TypeAdapterRuntimeTypeWrapper<K>(context, keyTypeAdapter, keyType); this.valueTypeAdapter = new TypeAdapterRuntimeTypeWrapper<V>(context, valueTypeAdapter, valueType); this.constructor = constructor; }
@Override public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { if (type != null && type.equals(String.class)) { return new JsonResponseBodyConverter<>(); } TypeAdapter<?> adapter = null; if (type != null) { adapter = gson.getAdapter(TypeToken.get(type)); } return new GsonResponseBodyConverter<>(gson, adapter); }
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); final TypeAdapter<JsonElement> elementTypeAdapter = gson.getAdapter(JsonElement.class); 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 jsonElement = elementTypeAdapter.read(in); if (jsonElement.isJsonObject()) { JsonObject jsonObject = jsonElement.getAsJsonObject(); if (jsonObject.has("status")) { int status = jsonObject.get("status").getAsInt(); String message = jsonObject.get("message").getAsString(); if (status == 0) { //do nothing } else { throw new ApiException(status, message); } } if (jsonObject.has(dataElementName)) { jsonElement = jsonObject.get(dataElementName); } } return delegate.fromJsonTree(jsonElement); } }.nullSafe(); }
@Override @SuppressWarnings("unchecked") public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { if (!Message.class.isAssignableFrom(typeToken.getRawType())) return null; return (TypeAdapter<T>) new Adapter(handler, gson); }
private static Gson getGson() { return new GsonBuilder() //动态注册优先于 @JsonAdapter .excludeFieldsWithoutExposeAnnotation() .registerTypeAdapter(IStudent.class, new TypeAdapter<IStudent>() { @Override public void write(JsonWriter out, IStudent value) throws IOException { log("write_getGson"); out.beginObject(); out.name("name").value("heaven7"); out.name("id").value("26"); out.endObject(); } @Override public IStudent read(JsonReader in) throws IOException { log("read_getGson"); StudentModuleImpl module = new StudentModuleImpl(); in.beginObject(); while (in.hasNext()){ switch (in.nextName()){ case "name": module.setName(in.nextString()); break; case "id": module.setAge(in.nextInt()); break; } } in.endObject(); return module; } }) .create(); }
private TypeAdapter<R> getAdapterFor(JsonElement element) { String field = extractor.apply(element); for (Map.Entry<Class<?>, Set<String>> entry : types.entrySet()) { if (entry.getValue().contains(field)) { return (TypeAdapter<R>) adapters.get(entry.getKey()); } } return null; }
public void write(JsonWriter out, T value) throws IOException { TypeAdapter chosen = this.delegate; Type runtimeType = getRuntimeTypeIfMoreSpecific(this.type, value); if (runtimeType != this.type) { TypeAdapter runtimeTypeAdapter = this.context.getAdapter(TypeToken.get(runtimeType)); if (!(runtimeTypeAdapter instanceof Adapter)) { chosen = runtimeTypeAdapter; } else if (this.delegate instanceof Adapter) { chosen = runtimeTypeAdapter; } else { chosen = this.delegate; } } chosen.write(out, value); }
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) { Class<?> rawType = type.getRawType(); final boolean skipSerialize = excludeClass(rawType, true); final boolean skipDeserialize = excludeClass(rawType, false); if (!skipSerialize && !skipDeserialize) { return null; } return new TypeAdapter<T>() { /** The delegate is lazily created because it may not be needed, and creating it may fail. */ private TypeAdapter<T> delegate; @Override public T read(JsonReader in) throws IOException { if (skipDeserialize) { in.skipValue(); return null; } return delegate().read(in); } @Override public void write(JsonWriter out, T value) throws IOException { if (skipSerialize) { out.nullValue(); return; } delegate().write(out, value); } private TypeAdapter<T> delegate() { TypeAdapter<T> d = delegate; return d != null ? d : (delegate = gson.getDelegateAdapter(Excluder.this, type)); } }; }
public static <TT> TypeAdapterFactory newFactory(final TypeToken<TT> type, final TypeAdapter<TT> typeAdapter) { return new TypeAdapterFactory() { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { return typeToken.equals(type) ? typeAdapter : null; } }; }
/** * Registers type adapters by implicit type. Adds one to read numbers in a {@code Map<String, * Object>} as Integers. */ static Gson create(Iterable<TypeAdapter<?>> adapters) { GsonBuilder builder = new GsonBuilder().setPrettyPrinting(); builder.registerTypeAdapter(new TypeToken<Map<String, Object>>() { }.getType(), new DoubleToIntMapTypeAdapter()); for (TypeAdapter<?> adapter : adapters) { Type type = resolveLastTypeParameter(adapter.getClass(), TypeAdapter.class); builder.registerTypeAdapter(type, adapter); } return builder.create(); }