List of usage examples for com.google.gson.internal.bind JsonTreeWriter JsonTreeWriter
public JsonTreeWriter()
From source file:com.gilecode.yagson.YaGson.java
License:Apache License
/** * This method serializes the specified object into its equivalent Json representation as a tree of * {@link JsonElement}s, given that the de-serialization type is known. * <p/>/*from w w w .j av a 2 s.co m*/ * The root type information is emitted only if necessary, i.e. if the specified de-serialization type differs from * the actual object's class. It is guaranteed that the resulting string may be de-serialized to the similar object * using {@code fromJson(json, deserializationType)}, unless some YaGson's features are disabled. * * @param src the object for which JSON representation is to be created * @param deserializationType The type which will be used for de-serialization of the resulting JSON representation * @return Json representation of {@code src} */ @Override public JsonElement toJsonTree(Object src, Type deserializationType) { if (src == null) { return JsonNull.INSTANCE; } boolean isRootTypeRequired = TypeUtils.isTypeInfoRequired(src.getClass(), deserializationType, false); JsonTreeWriter writer = new JsonTreeWriter(); super.toJson(src, src.getClass(), writer, isRootTypeRequired); return writer.get(); }
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/*from www. 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; }