List of usage examples for com.google.gson TypeAdapter TypeAdapter
TypeAdapter
From source file:com.vmware.xenon.common.serialization.SortedKeysMapViewAdapterFactory.java
License:Open Source License
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { if (!Map.class.isAssignableFrom(type.getRawType())) { return null; }/*w w w.j a v a2s .c o m*/ TypeAdapter<Map<String, ?>> orig = gson.getDelegateAdapter(this, TYPE); return new TypeAdapter<T>() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public void write(JsonWriter out, T value) throws IOException { if (value == null) { orig.write(out, null); return; } Map<String, ?> map = (Map) value; if (map.size() <= 1) { orig.write(out, map); } else { orig.write(out, new SortedKeysView(map)); } } @Override @SuppressWarnings("unchecked") public T read(JsonReader in) throws IOException { return (T) orig.read(in); } }; }
From source file:com.wix.mediaplatform.gson.RuntimeTypeAdapterFactory.java
License:Apache License
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) { if (null == type || !baseType.isAssignableFrom(type.getRawType())) { return null; }//from w w w . j a v a 2s . co m final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<>(); final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<>(); 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 = jsonElement.getAsJsonObject().get(typeFieldName); if (labelJsonElement == null) { throw new JsonParseException("cannot deserialize " + baseType + " because it does not define a field named " + typeFieldName); } String label = labelJsonElement.getAsString(); @SuppressWarnings("unchecked") // registration requires that subtype extends T 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); @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?"); } JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject(); // if (jsonObject.has(typeFieldName)) { // throw new JsonParseException("cannot serialize " + srcType.getName() // + " because it already defines a field named " + typeFieldName); // } JsonObject clone = new JsonObject(); // 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(); }
From source file:com.xpbytes.gson.hal.HalTypeAdapterFactory.java
License:Apache License
@Override public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) { final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); final TypeAdapter<JsonElement> basicAdapter = gson.getAdapter(JsonElement.class); // If we convert to JSON, isn't the deserializer more appropriate...? // Is this a HalResource? if (!HalReflection.isResource(type.getRawType())) return delegate; return new TypeAdapter<T>() { @Override/*from w w w . jav a2 s. co m*/ public void write(JsonWriter out, T value) throws IOException { delegate.write(out, value); } @Override public T read(JsonReader in) throws IOException { JsonElement fullJson = basicAdapter.read(in); Logger.getGlobal().log(Level.ALL, fullJson.toString()); T deserialized = delegate.fromJsonTree(fullJson); if (fullJson.isJsonObject()) { JsonObject fullJsonObject = fullJson.getAsJsonObject(); JsonObject linksObject = fullJsonObject.getAsJsonObject(HalConstants.RESERVED_LINKS_ROOT); JsonObject embeddedObject = fullJsonObject.getAsJsonObject(HalConstants.RESERVED_EMBEDDED_ROOT); List<Field> fieldsList = HalReflection.getHalFields(type.getRawType()); for (Field field : fieldsList) { if (HalReflection.isLink(field)) readLink(field, linksObject, deserialized); else if (HalReflection.isEmbed(field)) readEmbed(field, embeddedObject, deserialized); } } return deserialized; } private <A> void readEmbed(Field field, JsonObject rootObject, A deserialized) { HalEmbed embed = field.getAnnotation(HalEmbed.class); boolean optional = embed.optional(); if (rootObject == null && optional) return; String memberName = HalReflection.getJsonFieldName(embed, field); JsonParseException missingException = new JsonParseException( String.format(Locale.US, "Expected embed `%s` in the embedded root `%s` to be present", memberName, HalConstants.RESERVED_EMBEDDED_ROOT)); if (rootObject == null) throw missingException; boolean exists = rootObject.has(memberName); if (!exists) { if (optional) return; throw missingException; } Type innerType = HalReflection.getFieldItemizedType(field); //Class outerType = HalReflection.getFieldType( field ); JsonElement element = rootObject.get(memberName); // This gson.fromJson call will actually call into the proper stack to recursively // deserialize embeds and set their links where necessary. HalReflection.setEmbed(field, gson.fromJson(element, innerType), deserialized); } private <A> void readLink(Field field, JsonObject rootObject, A deserialized) { HalLink link = field.getAnnotation(HalLink.class); boolean optional = link.optional(); if (rootObject == null && optional) return; String memberName = HalReflection.getJsonFieldName(link, field); JsonParseException missingException = new JsonParseException( String.format(Locale.US, "Expected link `%s` in the links root `%s` to be present", memberName, HalConstants.RESERVED_LINKS_ROOT)); if (rootObject == null) throw missingException; boolean exists = rootObject.has(memberName); if (!exists) { if (optional) return; throw missingException; } // If this is not a descendant of a HalLinkObject, we better treat it as one. Class<?> innerType = HalReflection.getFieldItemizedType(field); if (!innerType.isAssignableFrom(HalLinkObject.class)) innerType = HalLinkObject.class; //Class outerType = HalReflection.getFieldType( field ); JsonElement element = rootObject.get(memberName); // TODO support collections /*if ( Collection.class.isAssignableFrom( outerType ) ) { innerType. //noinspection unchecked Class<Collection> collectionClass = (Class<Collection>)outerType; Collection collection = gson.fromJson( element, collectionClass ); } field.getType() if ( element.isJsonArray() ) { for ( JsonElement element1 : element.getAsJsonArray() ) HalReflection.setLink( field, , deserialized ); } else { */ HalReflection.setLink(field, (HalLinkObject) gson.fromJson(element, (Type) innerType), deserialized); } }.nullSafe(); }
From source file:cz.boris.gson.typeadapter.RuntimeTypeAdapterFactory.java
License:Apache License
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) { if (type.getRawType() != baseType) { return null; }//from w w w .j a v a 2 s . c o m 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 = 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(); @SuppressWarnings("unchecked") // registration requires that subtype extends T 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); @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?"); } JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject(); if (jsonObject.has(typeFieldName)) { throw new JsonParseException("cannot serialize " + srcType.getName() + " because it already defines a field named " + typeFieldName); } JsonObject clone = new JsonObject(); clone.add(typeFieldName, new JsonPrimitive(label)); for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) { clone.add(e.getKey(), e.getValue()); } Streams.write(clone, out); } }; }
From source file:data.RuntimeTypeAdapterFactory.java
License:Apache License
public <R> TypeAdapter<R> create(Gson g, TypeToken<R> type) { if (type == null || !baseType.isAssignableFrom(type.getRawType())) 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 = g.getDelegateAdapter(this, TypeToken.get(entry.getValue())); labelToDelegate.put(entry.getKey(), delegate); subtypeToDelegate.put(entry.getValue(), delegate); }/* www.j a v a2 s.co m*/ return new TypeAdapter<R>() { @Override public R read(JsonReader in) throws IOException { JsonElement jsonElement = Streams.parse(in); JsonElement 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(); @SuppressWarnings("unchecked") // registration requires that subtype extends T 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); @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?"); JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject(); if (jsonObject.has(typeFieldName)) throw new JsonParseException("cannot serialize " + srcType.getName() + " because it already defines a field named " + typeFieldName); JsonObject clone = new JsonObject(); 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(); }
From source file:data_storage.RuntimeTypeAdapterFactory.java
License:Apache License
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) { // if (type.getRawType() != baseType) { // return null; // }//from w ww.j a v a 2s . c om if (!baseType.isAssignableFrom(type.getRawType())) { 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 = 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(); @SuppressWarnings("unchecked") // registration requires that subtype extends T 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); @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?"); } JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject(); if (jsonObject.has(typeFieldName)) { throw new JsonParseException("cannot serialize " + srcType.getName() + " because it already defines a field named " + typeFieldName); } JsonObject clone = new JsonObject(); clone.add(typeFieldName, new JsonPrimitive(label)); for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) { clone.add(e.getKey(), e.getValue()); } Streams.write(clone, out); } }; }
From source file:de.bwravencl.controllerbuddy.json.ModeAwareTypeAdapterFactory.java
License:Open Source License
@Override public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) { final var delegate = gson.getDelegateAdapter(this, type); return new TypeAdapter<>() { @Override/*w w w . j a va2 s.c o m*/ public T read(final JsonReader in) throws IOException { final var obj = delegate.read(in); if (obj instanceof Mode) { final var mode = (Mode) obj; if (Profile.defaultMode.equals(mode)) mode.setDescription(rb.getString("DEFAULT_MODE_DESCRIPTION")); else if (OnScreenKeyboard.onScreenKeyboardMode.equals(mode)) mode.setDescription(rb.getString("ON_SCREEN_KEYBOARD_MODE_DESCRIPTION")); } return obj; } @Override public void write(final JsonWriter out, final T value) throws IOException { final var delegate = gson.getDelegateAdapter(ModeAwareTypeAdapterFactory.this, type); String prevDescription = null; try { if (value instanceof Mode) if (Profile.defaultMode.equals(value) || OnScreenKeyboard.onScreenKeyboardMode.equals(value)) { final var mode = (Mode) value; prevDescription = mode.getDescription(); mode.setDescription(null); } delegate.write(out, value); } finally { if (prevDescription != null) ((Mode) value).setDescription(prevDescription); } } }; }
From source file:de.chefkoch.api.serialize.RuntimeTypeAdapterFactory.java
License:Apache License
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) { if (type.getRawType() != baseType) { return null; }/* w w w. j a va2 s . c om*/ 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 = 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(); @SuppressWarnings("unchecked") // registration requires that subtype extends T 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 null; } return delegate.fromJsonTree(jsonElement); } @Override public void write(JsonWriter out, R value) throws IOException { Class<?> srcType = value.getClass(); String label = subtypeToLabel.get(srcType); @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?"); } JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject(); if (jsonObject.has(typeFieldName)) { throw new JsonParseException("cannot serialize " + srcType.getName() + " because it already defines a field named " + typeFieldName); } JsonObject clone = new JsonObject(); clone.add(typeFieldName, new JsonPrimitive(label)); for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) { clone.add(e.getKey(), e.getValue()); } Streams.write(clone, out); } }; }
From source file:de.lulebe.designer.external.RuntimeTypeAdapterFactory.java
License:Apache License
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) { if (type == null || !baseType.isAssignableFrom(type.getRawType())) { return null; }//from w w w.j a v a2 s . c o m 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 = 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(); @SuppressWarnings("unchecked") // registration requires that subtype extends T 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); @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?"); } JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject(); if (jsonObject.has(typeFieldName)) { throw new JsonParseException("cannot serialize " + srcType.getName() + " because it already defines a field named " + typeFieldName); } JsonObject clone = new JsonObject(); 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(); }
From source file:de.micromata.genome.junittools.wicket.models.WicketTestBuilderGsonBuilder.java
License:Apache License
public static Gson getGson() { if (gsonBuilder == null) { gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapterFactory(new TypeAdapterFactory() { @Override/*from ww w. j a va2 s .c o m*/ public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { if (type.getRawType() == Class.class) { return new TypeAdapter<T>() { @Override public void write(JsonWriter out, T value) throws IOException { out.value(((Class) value).getName()); } @Override public T read(JsonReader in) throws IOException { try { return (T) Class.forName(in.nextString()); } catch (ClassNotFoundException e) { LOG.error("unable to transform " + in.nextString() + " to a reasonable class, please check this!"); } return null; } }; } return null; } }); } return gsonBuilder.create(); }