List of usage examples for com.google.gson TypeAdapter read
public abstract T read(JsonReader in) throws IOException;
From source file:RestrictSerializationToBaseClassFactory.java
License:Apache License
@Override public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) { Class incoming = type.getRawType(); if (subClasses != null) { boolean matched = false; for (Class<? extends B> subClass : subClasses) { if (incoming == subClass) { matched = true;/*from w ww . j av a 2 s . com*/ break; } } if (!matched) return null; } else { // restricting all sub-classes since none specified // don't match the baseClass since we want to use the default factory for it if (incoming == baseClass || !baseClass.isAssignableFrom(incoming)) return null; } TypeAdapter<T> adapter = new TypeAdapter<T>() { @Override public T read(JsonReader reader) throws IOException { final TypeAdapter subAdapter = gson.getDelegateAdapter(RestrictSerializationToBaseClassFactory.this, type); return (T) subAdapter.read(reader); } @Override public void write(JsonWriter writer, T value) throws IOException { final TypeAdapter<B> baseAdapter = gson.getAdapter(baseClass); baseAdapter.write(writer, (B) value); } }; return adapter; }
From source file:cn.lambdalib.vis.model.renderer.ItemModelRenderer.java
License:MIT License
protected void readFromJson(String name, JsonReader in) throws IOException { TypeAdapter<CompTransform> cta = GsonAdapters.compTransformAdapter; switch (name) { case "t_std": stdTransform = cta.read(in); break;//from w ww . ja v a2s . c om case "t_fp": fpTransform = cta.read(in); break; case "t_tp": tpTransform = cta.read(in); break; case "texture": texture = GsonAdapters.resourceLocationAdapter.read(in); break; } }
From source file:co.aurasphere.botmill.kik.util.json.LowerCaseTypeAdapterFactory.java
License:Open Source License
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class); final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); return new TypeAdapter<T>() { @Override//w ww .j a v a2 s. co m public T read(JsonReader in) throws IOException { JsonElement tree = elementAdapter.read(in); afterRead(tree); return delegate.fromJsonTree(tree); } @Override public void write(JsonWriter out, T value) throws IOException { JsonElement tree = delegate.toJsonTree(value); beforeWrite(value, tree); elementAdapter.write(out, tree); } protected void beforeWrite(T source, JsonElement toSerialize) { } protected void afterRead(JsonElement deserialized) { if (deserialized instanceof JsonObject) { JsonObject jsonObject = ((JsonObject) deserialized); Set<Map.Entry<String, JsonElement>> entrySet = jsonObject.entrySet(); for (Map.Entry<String, JsonElement> entry : entrySet) { if (entry.getValue() instanceof JsonElement) { if (entry.getKey().equalsIgnoreCase("type")) { String val = jsonObject.get(entry.getKey()).toString(); jsonObject.addProperty(entry.getKey(), val.toLowerCase()); } } else { afterRead(entry.getValue()); } } } } }; }
From source file:co.mitro.core.servlets.ServerRejectsServlet.java
License:Open Source License
/** * Sets the server hints to hintsString, after validation. Throws exceptions if the JSON data * is incorrect, although the validation isn't currently extremely careful. *//*from ww w.ja va2 s. c om*/ public static void setServerHintsJson(String hintsString) { try { // Parse and validate the hints // TODO: Unit test this more carefully // can't use gson.fromJson() because it always uses lenient parsing; copied from there // See https://code.google.com/p/google-gson/issues/detail?id=372 JsonReader jsonReader = new JsonReader(new StringReader(hintsString)); TypeAdapter<?> typeAdapter = gson.getAdapter(TypeToken.get(listType)); @SuppressWarnings("unchecked") List<HintEntry> hints = (List<HintEntry>) typeAdapter.read(jsonReader); for (HintEntry hint : hints) { @SuppressWarnings("unused") Pattern regexp = Pattern.compile(hint.regex); if (hint.additional_submit_button_ids != null) { // optional: just don't include it instead of including an empty list assert hint.additional_submit_button_ids.size() > 0; for (String submitIds : hint.additional_submit_button_ids) { assert !Strings.isNullOrEmpty(submitIds); } } if (hint.allow_empty_username != null) { assert hint.allow_empty_username : "omit allow_empty_username if false"; } if (hint.empty_password_username_selector != null) { // TODO: Validate that this is a valid CSS selector? assert !hint.empty_password_username_selector .isEmpty() : "omit empty_password_username_selector if there is no selector"; assert hint.allow_empty_username != null && hint.allow_empty_username .booleanValue() : "allow_empty_username must be true if empty_password_username_selector is present"; } validateRules(hint.reject.login_submit); validateRules(hint.reject.submit); validateRules(hint.reject.password); validateRules(hint.reject.username); validateRules(hint.reject.form); } logger.info("setting {} server hints", hints.size()); serverHintsJson = hintsString; } catch (IOException | IllegalStateException e) { // Rethrow the same way as gson.fromJson() throw new JsonSyntaxException(e); } }
From source file:com.codefororlando.streettrees.api.deserializer.ResponseSanitizer.java
License:Open Source License
@Override 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);/*from ww w . j ava2 s . c om*/ } public T read(JsonReader in) throws IOException { T parsedObject = delegate.read(in); // NOTE(jpr): Tree names come in with errant whitespace, and its easiest to fix it here // rather than fighting retrofit during deserialization if (parsedObject instanceof Tree) { Tree tree = (Tree) parsedObject; tree.setTreeName(tree.getTreeName().trim()); } return parsedObject; } }; }
From source file:com.cyanogenmod.account.gcm.model.MessageTypeAdapterFactory.java
License:Apache License
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { if (!Message.class.isAssignableFrom(type.getRawType())) { return null; }//from ww w . ja v a 2 s.c om final TypeAdapter<Message> rootAdapter = gson.getDelegateAdapter(this, TypeToken.get(Message.class)); final TypeAdapter<PublicKeyMessage> keyExchangeAdapter = gson.getDelegateAdapter(this, TypeToken.get(PublicKeyMessage.class)); final TypeAdapter<SymmetricKeyMessage> symmetricKeyAdapter = gson.getDelegateAdapter(this, TypeToken.get(SymmetricKeyMessage.class)); final TypeAdapter<EncryptedMessage> secureMessageAdapter = gson.getDelegateAdapter(this, TypeToken.get(EncryptedMessage.class)); final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class); TypeAdapter<Message> result = new TypeAdapter<Message>() { @Override public void write(JsonWriter out, Message value) throws IOException { if (value instanceof PublicKeyMessage) { keyExchangeAdapter.write(out, (PublicKeyMessage) value); } else if (value instanceof SymmetricKeyMessage) { symmetricKeyAdapter.write(out, (SymmetricKeyMessage) value); } else if (value instanceof EncryptedMessage) { secureMessageAdapter.write(out, (EncryptedMessage) value); } else { JsonObject object = rootAdapter.toJsonTree(value).getAsJsonObject(); elementAdapter.write(out, object); } } @Override public Message read(JsonReader in) throws IOException { JsonObject object = elementAdapter.read(in).getAsJsonObject(); if (object.has("public_key")) { return keyExchangeAdapter.fromJsonTree(object); } else if (object.has("symmetric_key")) { return symmetricKeyAdapter.fromJsonTree(object); } else if (object.has("ciphertext")) { return secureMessageAdapter.fromJsonTree(object); } else { return rootAdapter.fromJsonTree(object); } } }.nullSafe(); return (TypeAdapter<T>) result; }
From source file:com.drakeet.rebase.api.tool.ResponseTypeAdapterFactory.java
License:Open Source License
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { final TypeAdapter<T> delegateAdapter = gson.getDelegateAdapter(this, type); final TypeAdapter<JsonElement> jsonElementAdapter = gson.getAdapter(JsonElement.class); return new TypeAdapter<T>() { @Override//from w ww . j a va 2 s . c o m public void write(JsonWriter out, T value) throws IOException { delegateAdapter.write(out, value); } @Override @SuppressWarnings("PointlessBooleanExpression") public T read(JsonReader in) throws IOException { JsonElement jsonElement = jsonElementAdapter.read(in); if (jsonElement.isJsonObject()) { JsonObject jsonObject = jsonElement.getAsJsonObject(); if (jsonObject.has(ERROR) && jsonObject.get(ERROR).getAsBoolean() == false) { if (jsonObject.has(DATA) && isJson(jsonObject, DATA)) { jsonElement = jsonObject.get(DATA); } } } return delegateAdapter.fromJsonTree(jsonElement); } }.nullSafe(); }
From source file:com.flipkart.android.proteus.demo.converter.GsonResponseBodyConverter.java
License:Apache License
@Override public T convert(ResponseBody value) throws IOException { TypeAdapter<T> adapter = getAdapter(); JsonReader jsonReader = gson.newJsonReader(value.charStream()); jsonReader.setLenient(true);//from w w w .j a v a 2s. com try { return adapter.read(jsonReader); } finally { value.close(); } }
From source file:com.flipkart.batching.gson.RuntimeTypeAdapterFactory.java
License:Open Source License
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) { if (type.getRawType() != baseType) { return null; }/*from w w w . ja v a2 s . 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 = labelToTypeAdapter.get(entry.getKey()); if (delegate == null) { 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 reader) throws IOException { if (reader.peek() == com.google.gson.stream.JsonToken.NULL) { reader.nextNull(); return null; } if (reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null; } reader.beginObject(); String label = null; R result = null; while (reader.hasNext()) { String name = reader.nextName(); com.google.gson.stream.JsonToken jsonToken = reader.peek(); if (jsonToken == com.google.gson.stream.JsonToken.NULL) { reader.skipValue(); continue; } switch (name) { case "type": label = TypeAdapters.STRING.read(reader); break; case "value": @SuppressWarnings("unchecked") // registration requires that subtype extends T TypeAdapter<R> delegate = label == null ? null : (TypeAdapter<R>) labelToDelegate.get(label); if (delegate == null) { throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label + "; did you forget to register a subtype?"); } result = delegate.read(reader); break; default: reader.skipValue(); break; } } reader.endObject(); return result; } @Override public void write(JsonWriter out, R value) throws IOException { Class<?> srcType = value.getClass(); @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?"); } String label = subtypeToLabel.get(srcType); out.beginObject(); out.name("type"); out.value(label); out.name("value"); delegate.write(out, value); out.endObject(); } }.nullSafe(); }
From source file:com.google.caliper.json.ImmutableListTypeAdatperFactory.java
License:Apache License
@SuppressWarnings("unchecked") @Override//from w w w. jav a 2s . co m public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { Type type = typeToken.getType(); if (typeToken.getRawType() != ImmutableList.class || !(type instanceof ParameterizedType)) { return null; } com.google.common.reflect.TypeToken<ImmutableList<?>> betterToken = (com.google.common.reflect.TypeToken<ImmutableList<?>>) com.google.common.reflect.TypeToken .of(typeToken.getType()); final TypeAdapter<ArrayList<?>> arrayListAdapter = (TypeAdapter<ArrayList<?>>) gson.getAdapter( TypeToken.get(betterToken.getSupertype(List.class).getSubtype(ArrayList.class).getType())); return new TypeAdapter<T>() { @Override public void write(JsonWriter out, T value) throws IOException { ArrayList<?> arrayList = Lists.newArrayList((List<?>) value); arrayListAdapter.write(out, arrayList); } @Override public T read(JsonReader in) throws IOException { ArrayList<?> arrayList = arrayListAdapter.read(in); return (T) ImmutableList.copyOf(arrayList); } }; }