use of com.google.gson.TypeAdapter in project immutables by immutables.
the class GsonCodecs method typeAdapterFromCodec.
/**
* Build a TypeAdapter from {@link Codec} opposite of {@link #codecFromTypeAdapter(Class, TypeAdapter)}.
*
* @param codec existing codec
* @return type adapter which delegates calls to a codec.
*/
public static <T> TypeAdapter<T> typeAdapterFromCodec(final Codec<T> codec) {
Preconditions.checkNotNull(codec, "codec");
return new TypeAdapter<T>() {
@Override
public void write(JsonWriter out, T value) throws IOException {
BsonWriter writer = (BsonWriter) out;
org.bson.BsonWriter delegate = writer.unwrap();
codec.encode(delegate, value, EncoderContext.builder().build());
}
@Override
public T read(JsonReader in) throws IOException {
BsonReader reader = (BsonReader) in;
org.bson.BsonReader delegate = reader.unwrap();
return codec.decode(delegate, DecoderContext.builder().build());
}
};
}
use of com.google.gson.TypeAdapter in project immutables by immutables.
the class Marshaling method toJson.
@SuppressWarnings({ "resource", "unchecked" })
public static String toJson(Object object) {
TypeAdapter<Object> adapter = GSON.getAdapter((TypeToken<Object>) TypeToken.get(object.getClass()));
try {
StringWriter stringWriter = new StringWriter();
JsonGeneratorWriter writer = new JsonGeneratorWriter(JSON_FACTORY.createGenerator(stringWriter));
if (adapter instanceof com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.Adapter) {
throw new IllegalStateException("Immutable adapters not registered");
}
GSON.toJson(object, object.getClass(), writer);
writer.close();
return stringWriter.toString();
} catch (IOException ex) {
throw Throwables.propagate(ex);
}
}
use of com.google.gson.TypeAdapter in project gocd by gocd.
the class RuntimeTypeAdapterFactory method create.
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
if (type.getRawType() != baseType) {
return null;
}
final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>();
final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>();
for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
TypeAdapter<?> 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 in) throws IOException {
JsonElement jsonElement = Streams.parse(in);
JsonElement labelJsonElement;
if (maintainType) {
labelJsonElement = jsonElement.getAsJsonObject().get(typeFieldName);
} else {
labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName);
}
if (labelJsonElement == null) {
throw new JsonParseException("cannot deserialize " + baseType + " because it does not define a field named " + typeFieldName);
}
String label = labelJsonElement.getAsString();
// registration requires that subtype extends T
@SuppressWarnings("unchecked") TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);
if (delegate == null) {
throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label + "; did you forget to register a subtype?");
}
return delegate.fromJsonTree(jsonElement);
}
@Override
public void write(JsonWriter out, R value) throws IOException {
Class<?> srcType = value.getClass();
String label = subtypeToLabel.get(srcType);
// registration requires that subtype extends T
@SuppressWarnings("unchecked") 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?");
}
JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
if (maintainType) {
Streams.write(jsonObject, out);
return;
}
JsonObject clone = new JsonObject();
if (jsonObject.has(typeFieldName)) {
throw new JsonParseException("cannot serialize " + srcType.getName() + " because it already defines a field named " + typeFieldName);
}
clone.add(typeFieldName, new JsonPrimitive(label));
for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
clone.add(e.getKey(), e.getValue());
}
Streams.write(clone, out);
}
}.nullSafe();
}
use of com.google.gson.TypeAdapter in project Terasology by MovingBlocks.
the class PolymorphicTypeAdapterFactory method create.
@Override
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
if (!baseClass.isAssignableFrom(type.getRawType())) {
return null;
}
return new TypeAdapter<R>() {
@SuppressWarnings("unchecked")
@Override
public void write(JsonWriter out, R value) throws IOException {
Class<?> valueClass = value.getClass();
String valueTypeName = valueClass.getName();
TypeToken<?> valueType = TypeToken.get(valueClass);
TypeAdapter<R> delegate = (TypeAdapter<R>) gson.getDelegateAdapter(PolymorphicTypeAdapterFactory.this, valueType);
if (delegate == null) {
throw new JsonParseException("Could not serialize " + valueClass.getName());
}
JsonElement jsonElement = delegate.toJsonTree(value);
if (valueClass != baseClass) {
JsonObject jsonObject = jsonElement.getAsJsonObject();
JsonObject clone = new JsonObject();
clone.add(TYPE_FIELD_NAME, new JsonPrimitive(valueTypeName));
for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
clone.add(e.getKey(), e.getValue());
}
Streams.write(clone, out);
} else {
Streams.write(jsonElement, out);
}
}
@SuppressWarnings("unchecked")
@Override
public R read(JsonReader in) throws IOException {
JsonElement jsonElement = Streams.parse(in);
Class<?> valueClass;
if (jsonElement.isJsonObject()) {
JsonElement typeNameJsonElement = jsonElement.getAsJsonObject().remove(TYPE_FIELD_NAME);
if (typeNameJsonElement != null) {
String typeName = typeNameJsonElement.getAsString();
try {
valueClass = Class.forName(typeName);
} catch (ClassNotFoundException e) {
throw new JsonParseException("Could not find class " + typeName);
}
} else {
valueClass = baseClass;
}
} else {
valueClass = baseClass;
}
if (!baseClass.isAssignableFrom(valueClass)) {
throw new JsonParseException(valueClass.getName() + " does not derive from " + baseClass.getName());
}
TypeToken<?> valueType = TypeToken.get(valueClass);
TypeAdapter<R> delegate = (TypeAdapter<R>) gson.getDelegateAdapter(PolymorphicTypeAdapterFactory.this, valueType);
if (delegate == null) {
throw new JsonParseException("Could not deserialize " + valueClass.getName());
}
return delegate.fromJsonTree(jsonElement);
}
};
}
use of com.google.gson.TypeAdapter in project LanternServer by LanternPowered.
the class CatalogTypeTypeAdapterFactory method create.
@Nullable
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
final Class<? super T> raw = type.getRawType();
if (!CatalogType.class.isAssignableFrom(raw)) {
return null;
}
final TypeAdapter<JsonElement> jsonElementTypeAdapter = gson.getAdapter(JsonElement.class);
return new TypeAdapter<T>() {
@Override
public void write(JsonWriter out, T value) throws IOException {
jsonElementTypeAdapter.write(out, new JsonPrimitive(((CatalogType) value).getId()));
}
@Override
public T read(JsonReader in) throws IOException {
final String id = jsonElementTypeAdapter.read(in).getAsString();
// noinspection unchecked
return (T) Sponge.getRegistry().getType((Class<? extends CatalogType>) raw, id).orElseThrow(() -> new IllegalArgumentException("There does not exist a " + raw.getName() + " with id: " + id));
}
};
}
Aggregations