Java Code Examples for com.google.gson.Gson#getDelegateAdapter()

The following examples show how to use com.google.gson.Gson#getDelegateAdapter() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Adapter.java    From SoundCloud-API with MIT License 6 votes vote down vote up
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);

    return new TypeAdapter<T>() {
        public void write(JsonWriter out, T value) throws IOException {
            delegate.write(out, value);
        }

        public T read(JsonReader in) throws IOException {
            T obj = delegate.read(in);
            if (obj instanceof PostProcessable) {
                ((PostProcessable)obj).postProcess();
            }
            return obj;
        }
    };
}
 
Example 2
Source File: GsonPostProcessEnablingTypeFactory.java    From intellij-spring-assistant with MIT License 6 votes vote down vote up
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
  TypeAdapter<T> delegateAdapter = gson.getDelegateAdapter(this, typeToken);

  return new TypeAdapter<T>() {
    @Override
    public void write(JsonWriter jsonWriter, T value) throws IOException {
      delegateAdapter.write(jsonWriter, value);
    }

    @Override
    public T read(JsonReader jsonReader) throws IOException {
      T obj = delegateAdapter.read(jsonReader);
      if (obj instanceof GsonPostProcessable) {
        GsonPostProcessable.class.cast(obj).doOnGsonDeserialization();
      }
      return obj;
    }
  };
}
 
Example 3
Source File: Adapter.java    From last.fm-api with MIT License 6 votes vote down vote up
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);

    return new TypeAdapter<T>() {
        public void write(JsonWriter out, T value) throws IOException {
            delegate.write(out, value);
        }

        public T read(JsonReader in) throws IOException {
            T obj = delegate.read(in);
            if (obj instanceof PostProcessable) {
                ((PostProcessable)obj).postProcess();
            }
            return obj;
        }
    };
}
 
Example 4
Source File: SafeListAdapter.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> tokenType) {
    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, tokenType);

    return new TypeAdapter<T>() {
        @Override
        public void write(JsonWriter out, T value) throws IOException {
            delegate.write(out, value);
        }

        @Override
        public T read(JsonReader arg0) throws IOException {
            final T t = delegate.read(arg0);
            if (List.class.isAssignableFrom(tokenType.getRawType())) {
                if (t == null) {
                    return (T) Collections.EMPTY_LIST;
                }

                final List<?> list = (List<?>) t;
                return (T) Collections.unmodifiableList(list);
            }
            return t;
        }
    };
}
 
Example 5
Source File: GsonJsonMarshallerFactory.java    From softlayer-java with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    if (!List.class.isAssignableFrom(type.getRawType()) || !(type.getType() instanceof ParameterizedType)) {
        return null;
    }
    Type[] typeArgs = ((ParameterizedType) type.getType()).getActualTypeArguments();
    if (typeArgs.length != 1 || !(typeArgs[0] instanceof Class)) {
        return null;
    }
    return new ListOrSingleObjectTypeAdapter(gson.getDelegateAdapter(this, type),
        gson.getAdapter((Class) typeArgs[0]));
}
 
Example 6
Source File: InterceptorFactory.java    From gson with Apache License 2.0 5 votes vote down vote up
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
  Intercept intercept = type.getRawType().getAnnotation(Intercept.class);
  if (intercept == null) {
    return null;
  }

  TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
  return new InterceptorAdapter<T>(delegate, intercept);
}
 
Example 7
Source File: Excluder.java    From gson with Apache License 2.0 5 votes vote down vote up
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
  Class<?> rawType = type.getRawType();
  boolean excludeClass = excludeClassChecks(rawType);

  final boolean skipSerialize = excludeClass || excludeClassInStrategy(rawType, true);
  final boolean skipDeserialize = excludeClass ||  excludeClassInStrategy(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));
    }
  };
}
 
Example 8
Source File: GsonCodecs.java    From immutables with Apache License 2.0 5 votes vote down vote up
/**
 * 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.
 */
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;
      }

    }
  };
}
 
Example 9
Source File: PostTypeAdapterFactory.java    From quill with MIT License 5 votes vote down vote up
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    @SuppressWarnings("unchecked")
    Class<T> rawType = (Class<T>) type.getRawType();
    if (rawType != Post.class) {
        return null;
    }

    final TypeAdapter delegate = gson.getDelegateAdapter(this, type);
    //noinspection unchecked
    return (TypeAdapter<T>) new TypeAdapter<Post>() {
        @Override
        public void write(JsonWriter out, Post value) throws IOException {
            //noinspection unchecked
            delegate.write(out, value);
        }

        @Override
        public Post read(JsonReader in) throws IOException {
            Post post = (Post) delegate.read(in);

            // Empty posts imported from Ghost 0.11.x have mobiledoc == null, which is incorrect
            // but we do need to handle it. Drafts created in Ghost 1.0 on the other hand, do
            // have mobiledoc set to a valid, empty mobiledoc document.
            if (post.getMobiledoc() != null && !post.getMobiledoc().isEmpty()) {
                // Post JSON example:
                // {
                //   "mobiledoc": "{\"version\": \"0.3.1\", ... }",
                //   ...
                // }
                post.setMarkdown(GhostApiUtils.mobiledocToMarkdown(post.getMobiledoc()));
            } else {
                post.setMarkdown("");
            }
            return post;
        }
    };
}
 
Example 10
Source File: AutoMatterTypeAdapter.java    From auto-matter with Apache License 2.0 5 votes vote down vote up
static <T> AutoMatterTypeAdapter<T> createForValue(
    final Gson gson,
    final TypeAdapterFactory skipFactory,
    final TypeToken<T> type,
    final Map<String, List<String>> serializedNameMethods
) {
  return new AutoMatterTypeAdapter<>(gson,
                                     gson.getDelegateAdapter(skipFactory, type),
                                     serializedNameMethods);
}
 
Example 11
Source File: ItemTypeAdapterFactory.java    From Varis-Android with Apache License 2.0 5 votes vote down vote up
public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) {

        final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
        final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);

        return new TypeAdapter<T>() {

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

            public T read(JsonReader in) throws IOException {

                JsonElement jsonElement = elementAdapter.read(in);
                if (jsonElement.isJsonObject()) {
                    JsonObject jsonObject = jsonElement.getAsJsonObject();
                    // fetch repositories
                    if (jsonObject.has("repos") && jsonObject.get("repos").isJsonArray()) {
                        jsonElement = jsonObject.get("repos");
                    }

                    // fetch user
                    if (jsonObject.has("user") && jsonObject.get("user").isJsonObject()) {
                        jsonElement = jsonObject.get("user");
                    }

                    // NOTE Add more objects here, if needed
                }

                return delegate.fromJsonTree(jsonElement);
            }
        }.nullSafe();
    }
 
Example 12
Source File: ItemTypeAdapterFactory.java    From Movie-Check with Apache License 2.0 5 votes vote down vote up
public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) {

        final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
        final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);

        return new TypeAdapter<T>() {

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

            public T read(JsonReader in) throws IOException {

                JsonElement jsonElement = elementAdapter.read(in);
                JsonElement newJsonElement = null;
                if (jsonElement.isJsonObject()) {
                    JsonObject jsonObject = jsonElement.getAsJsonObject();
                    for (int i = 0; i < rootNameList.size(); i++) {
                        if (jsonObject.has(rootNameList.get(i))) {
                            if(newJsonElement == null) {
                                newJsonElement = jsonObject.get(rootNameList.get(i));
                            } else {
                                ((JsonArray) newJsonElement).addAll(jsonObject.getAsJsonArray(rootNameList.get(i)));
                            }
                        }
                    }
                }

                return delegate.fromJsonTree(newJsonElement != null ? newJsonElement : jsonElement );
            }
        }.nullSafe();
    }
 
Example 13
Source File: GsonAutoValueSpeakerTest.java    From Jolyglot with Apache License 2.0 5 votes vote down vote up
@Override protected Jolyglot jolyglot() {
  return new GsonAutoValueSpeaker() {
    @Override protected TypeAdapterFactory autoValueGsonTypeAdapterFactory() {
      return new TypeAdapterFactory() {
        @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
          return gson.getDelegateAdapter(this, type);
        }
      };
    }
  };
}
 
Example 14
Source File: GsonAutoValueSpeakerGenericsTest.java    From Jolyglot with Apache License 2.0 5 votes vote down vote up
@Override protected JolyglotGenerics jolyglot() {
  return new GsonAutoValueSpeaker() {
    @Override protected TypeAdapterFactory autoValueGsonTypeAdapterFactory() {
      return new TypeAdapterFactory() {
        @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
          return gson.getDelegateAdapter(this, type);
        }
      };
    }
  };
}
 
Example 15
Source File: DataTypeAdapterFactory.java    From mvvm-starter with MIT License 5 votes vote down vote up
@Override
public <T> TypeAdapter<T> create (Gson gson, TypeToken<T> type)
{
    final TypeAdapter<T>           lDelegate       = gson.getDelegateAdapter(this, type);
    final TypeAdapter<JsonElement> lElementAdapter = gson.getAdapter(JsonElement.class);

    return new TypeAdapter<T>()
    {
        @Override
        public void write (JsonWriter out, T value) throws IOException
        {
            lDelegate.write(out, value);
        }

        @Override
        public T read (JsonReader in) throws IOException
        {
            JsonElement lElement = lElementAdapter.read(in);
            if (lElement.isJsonObject())
            {
                JsonObject lObject = lElement.getAsJsonObject();
                if (lObject.has("data"))
                {
                    lElement = lObject.get("data");
                }
            }
            return lDelegate.fromJsonTree(lElement);
        }
    };
}
 
Example 16
Source File: JsonAdapterNullSafeTest.java    From gson with Apache License 2.0 5 votes vote down vote up
@Override public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) {
  if (type.getRawType() != Device.class || recursiveCall.get() != null) {
    recursiveCall.set(null); // clear for subsequent use
    return null;
  }
  recursiveCall.set(Boolean.TRUE);
  return gson.getDelegateAdapter(this, type);
}
 
Example 17
Source File: HistoryFragmentVM.java    From chaoli-forum-for-android-2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    if (type.getRawType() != HistoryItem.Data.class) return null;

    TypeAdapter<HistoryItem.Data> defaultAdapter = (TypeAdapter<HistoryItem.Data>) gson.getDelegateAdapter(this, type);
    return (TypeAdapter<T>) new DataAdapter(defaultAdapter);

}
 
Example 18
Source File: LowercaseEnumTypeAdapterFactory.java    From messenger4j with MIT License 5 votes vote down vote up
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {

  @SuppressWarnings("unchecked")
  final Class<T> rawType = (Class<T>) type.getRawType();
  if (!rawType.isEnum()) {
    return null;
  }

  final TypeAdapter<T> delegateAdapter = gson.getDelegateAdapter(this, type);
  final Map<String, T> transformedToConstant = new HashMap<>();
  final Map<T, String> constantToTransformed = new HashMap<>();
  for (T constant : rawType.getEnumConstants()) {
    final String transformedConstant = transform(constant, delegateAdapter);
    transformedToConstant.put(transformedConstant, constant);
    constantToTransformed.put(constant, transformedConstant);
  }

  return new TypeAdapter<T>() {
    @Override
    public void write(JsonWriter out, T value) throws IOException {
      if (value == null) {
        out.nullValue();
      } else {
        out.value(constantToTransformed.get(value));
      }
    }

    @Override
    public T read(JsonReader reader) throws IOException {
      if (reader.peek() == JsonToken.NULL) {
        reader.nextNull();
        return null;
      } else {
        return transformedToConstant.get(reader.nextString());
      }
    }
  };
}
 
Example 19
Source File: ProblemAdapterFactory.java    From problem with MIT License 5 votes vote down vote up
private TypeAdapter<T> createCustomAdapter(
        final Gson gson, final TypeToken<T> type) {

    return new CustomProblemAdapter<>(
            gson,
            gson.getDelegateAdapter(
                    ProblemAdapterFactory.this,
                    type),
            stackTraces);
}
 
Example 20
Source File: ResourceOperationTypeAdapter.java    From lsp4j with Eclipse Public License 2.0 4 votes vote down vote up
InnerResourceOperationTypeAdapter(TypeAdapterFactory factory, Gson gson) {
	createFileAdapter = gson.getDelegateAdapter(factory, TypeToken.get(CreateFile.class));
	deleteFileAdapter = gson.getDelegateAdapter(factory, TypeToken.get(DeleteFile.class));
	renameFileAdapter = gson.getDelegateAdapter(factory, TypeToken.get(RenameFile.class));
}