List of usage examples for com.google.gson TypeAdapter write
public abstract void write(JsonWriter out, T value) throws IOException;
From source file:com.twitter.sdk.android.core.models.SafeListAdapter.java
License:Apache License
@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//w w w. j av a 2 s . com 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; } }; }
From source file:com.twitter.sdk.android.core.models.SafeMapAdapter.java
License:Apache License
@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//from w w w . j a v a2s . c om 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 (Map.class.isAssignableFrom(tokenType.getRawType())) { if (t == null) { return (T) Collections.EMPTY_MAP; } final Map<?, ?> map = (Map<?, ?>) t; return (T) Collections.unmodifiableMap(map); } return t; } }; }
From source file:com.vaadin.addon.charts.model.gsonhelpers.AbstractSeriesTypeAdapterFactory.java
private TypeAdapter<AbstractSeries> customizeMyClassAdapter(Gson gson, TypeToken<AbstractSeries> type) { final TypeAdapter<AbstractSeries> delegate = gson.getDelegateAdapter(this, type); final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class); return new TypeAdapter<AbstractSeries>() { @Override/* www. jav a2 s .c o m*/ public void write(JsonWriter out, AbstractSeries value) throws IOException { JsonObject tree = (JsonObject) delegate.toJsonTree(value); // "flatten" series specific plot options at series level. see // Higchart API for details if (value.getPlotOptions() != null) { JsonObject plotOptionsJson = (JsonObject) tree.remove("plotOptions"); if (plotOptionsJson != null) { Set<Entry<String, JsonElement>> entrySet = plotOptionsJson.entrySet(); for (Entry<String, JsonElement> entry : entrySet) { tree.add(entry.getKey(), entry.getValue()); } tree.addProperty("type", value.getPlotOptions().getChartType().toString()); } } elementAdapter.write(out, tree); } // This is never used @Override public AbstractSeries read(JsonReader in) throws IOException { JsonElement tree = elementAdapter.read(in); return delegate.fromJsonTree(tree); } }; }
From source file:com.vaadin.addon.charts.model.gsonhelpers.DataSeriesItemTypeAdapterFactory.java
private TypeAdapter<DataSeriesItem> customizeMyClassAdapter(Gson gson, TypeToken<DataSeriesItem> type) { final TypeAdapter<DataSeriesItem> delegate = gson.getDelegateAdapter(this, type); final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class); return new TypeAdapter<DataSeriesItem>() { @Override/*from ww w . j a v a 2 s . c o m*/ public void write(JsonWriter out, DataSeriesItem value) throws IOException { if (value.isCustomized()) { elementAdapter.write(out, delegate.toJsonTree(value)); } else { Number x = value.getX(); Number y = value.getY(); if (x != null) { JsonArray jsonArray = new JsonArray(); jsonArray.add(new JsonPrimitive(x)); if (y != null) { jsonArray.add(new JsonPrimitive(y)); } else if (value.getLow() != null) { jsonArray.add(new JsonPrimitive(value.getLow())); jsonArray.add(new JsonPrimitive(value.getHigh())); } else { jsonArray.add(JsonNull.INSTANCE); jsonArray.add(JsonNull.INSTANCE); } elementAdapter.write(out, jsonArray); } else { // If no x set, make it like list series, just number or // min-max pairs if (y != null) { elementAdapter.write(out, new JsonPrimitive(y)); } else { JsonArray jsonArray = new JsonArray(); jsonArray.add(new JsonPrimitive(value.getLow())); jsonArray.add(new JsonPrimitive(value.getHigh())); elementAdapter.write(out, jsonArray); } } } } // This is never used @Override public DataSeriesItem read(JsonReader in) throws IOException { JsonElement tree = elementAdapter.read(in); return delegate.fromJsonTree(tree); } }; }
From source file:com.vaadin.addon.charts.model.gsonhelpers.TitleTypeAdapterFactory.java
private TypeAdapter<Title> customizeMyClassAdapter(Gson gson, TypeToken<Title> type) { final TypeAdapter<Title> delegate = gson.getDelegateAdapter(this, type); final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class); return new TypeAdapter<Title>() { @Override/* w ww. ja v a2s . co m*/ public void write(JsonWriter out, Title value) throws IOException { // null for text is significant, else there will be // "Chart Title" as default if (value != null && value.getText() == null) { boolean serializeNulls = out.getSerializeNulls(); out.setSerializeNulls(true); out.beginObject(); out.name("text"); out.nullValue(); out.endObject(); out.setSerializeNulls(serializeNulls); } else { elementAdapter.write(out, delegate.toJsonTree(value)); } } // This is never used @Override public Title read(JsonReader in) throws IOException { JsonElement tree = elementAdapter.read(in); return delegate.fromJsonTree(tree); } }; }
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 a2 s.co 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.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. ja v a 2 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:edu.mit.media.funf.config.ContextInjectorTypeAdapaterFactory.java
License:Open Source License
@Override public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) { final TypeAdapter<T> delegateAdapter = delegate.create(gson, type); if (delegateAdapter == null) { return null; } else {//from ww w.java2 s .co m return new TypeAdapter<T>() { @Override public void write(JsonWriter out, T value) throws IOException { delegateAdapter.write(out, value); } @Override public T read(JsonReader in) throws IOException { T value = delegateAdapter.read(in); if (value != null) { try { Field contextField = AnnotationUtil.getField(CONTEXT_FIELD, value.getClass()); if (contextField != null && Context.class.isAssignableFrom(contextField.getType())) { boolean isAccessible = contextField.isAccessible(); contextField.setAccessible(true); contextField.set(value, context); contextField.setAccessible(isAccessible); } } catch (SecurityException e) { // Swallow Log.v(TAG, e.getMessage()); } catch (IllegalArgumentException e) { // Swallow Log.v(TAG, e.getMessage()); } catch (IllegalAccessException e) { // Swallow Log.v(TAG, e.getMessage()); } } return value; } }; } }
From source file:edu.mit.media.funf.config.DefaultRuntimeTypeAdapterFactory.java
License:Open Source License
@Override public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) { if (baseClass.isAssignableFrom(type.getRawType())) { return new TypeAdapter<T>() { @Override/*ww w. j a v a 2 s.c om*/ public void write(JsonWriter out, T value) throws IOException { if (value == null) { out.nullValue(); return; } // TODO: cache these only once per runtime type final TypeAdapter delegate = delegateFactory.create(gson, TypeToken.get(value.getClass())); JsonTreeWriter treeWriter = new JsonTreeWriter(); delegate.write(treeWriter, value); JsonElement el = treeWriter.get(); if (el.isJsonObject()) { JsonObject elObject = el.getAsJsonObject(); elObject.addProperty(RuntimeTypeAdapterFactory.TYPE, value.getClass().getName()); Streams.write(elObject, out); } else { Streams.write(el, out); } } @Override public T read(JsonReader in) throws IOException { // TODO: need to handle null JsonElement el = Streams.parse(in); Class<? extends T> runtimeType = getRuntimeType(el, type); if (runtimeType == null) { throw new ParseException("RuntimeTypeAdapter: Unable to parse runtime type."); } // TODO: cache these only once per runtime type final TypeAdapter<? extends T> delegate = delegateFactory.create(gson, TypeToken.get(runtimeType)); if (el.isJsonPrimitive() && el.getAsJsonPrimitive().isString()) { JsonObject typeObject = new JsonObject(); typeObject.addProperty(TYPE, el.getAsString()); el = typeObject; } return delegate.read(new JsonTreeReader(el)); } }; } return null; }
From source file:edu.mit.media.funf.config.ListenerInjectorTypeAdapterFactory.java
License:Open Source License
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { final TypeAdapter<T> delegateAdapter = delegate.create(gson, type); if (delegateAdapter == null) { return null; } else {/*from www. j a va 2 s. c o m*/ return new TypeAdapter<T>() { @Override public void write(JsonWriter out, T value) throws IOException { delegateAdapter.write(out, value); } @Override public T read(JsonReader in) throws IOException { T value = delegateAdapter.read(in); if (value != null && value instanceof DataSource) { try { Field filtersField = AnnotationUtil.getField(ConfigRewriteUtil.FILTER_FIELD_NAME, value.getClass()); Field delegatorField = AnnotationUtil.getField(ConfigRewriteUtil.DELEGATOR_FIELD_NAME, value.getClass()); boolean isDelegatorAccessible = delegatorField.isAccessible(); delegatorField.setAccessible(true); DataListener delegator = (DataListener) delegatorField.get(value); if (filtersField != null && delegator != null) { boolean isAccessible = filtersField.isAccessible(); filtersField.setAccessible(true); Object existingFilter = filtersField.get(value); if (existingFilter == null) filtersField.set(value, delegator); else injectListener(existingFilter, delegator); filtersField.setAccessible(isAccessible); } delegatorField.setAccessible(isDelegatorAccessible); } catch (SecurityException e) { // Swallow Log.v(TAG, e.getMessage()); } catch (IllegalArgumentException e) { // Swallow Log.v(TAG, e.getMessage()); } catch (IllegalAccessException e) { // Swallow Log.v(TAG, e.getMessage()); } } return value; } private void injectListener(Object value, DataListener listener) { try { Field listenerField = AnnotationUtil.getField(ConfigRewriteUtil.LISTENER_FIELD_NAME, value.getClass()); if (listenerField != null && DataListener.class.isAssignableFrom(listenerField.getType())) { boolean isAccessible = listenerField.isAccessible(); listenerField.setAccessible(true); Object existingListener = listenerField.get(value); if (existingListener == null) listenerField.set(existingListener, listener); else injectListener(existingListener, listener); listenerField.setAccessible(isAccessible); return; } } catch (SecurityException e) { // Swallow Log.v(TAG, e.getMessage()); } catch (IllegalArgumentException e) { // Swallow Log.v(TAG, e.getMessage()); } catch (IllegalAccessException e) { // Swallow Log.v(TAG, e.getMessage()); } try { Field targetField = AnnotationUtil.getField(ConfigRewriteUtil.TARGET_FIELD_NAME, value.getClass()); if (targetField != null) { boolean isAccessible = targetField.isAccessible(); targetField.setAccessible(true); Object existingTarget = targetField.get(value); if (existingTarget != null) injectListener(existingTarget, listener); targetField.setAccessible(isAccessible); return; } } catch (SecurityException e) { // Swallow Log.v(TAG, e.getMessage()); } catch (IllegalArgumentException e) { // Swallow Log.v(TAG, e.getMessage()); } catch (IllegalAccessException e) { // Swallow Log.v(TAG, e.getMessage()); } if (value instanceof DataSource) { ((DataSource) value).setListener(listener); return; } } }; } }