List of usage examples for com.google.gson TypeAdapter read
public abstract T read(JsonReader in) throws IOException;
From source file:io.plaidapp.core.data.api.DenvelopingConverter.java
License:Apache License
@Override public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {/*ww w . j a v a2s.co m*/ // This converter requires an annotation providing the name of the payload in the envelope; // if one is not supplied then return null to continue down the converter chain. final String payloadName = getPayloadName(annotations); if (payloadName == null) return null; final TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type)); return (Converter<ResponseBody, Object>) body -> { try (JsonReader jsonReader = gson.newJsonReader(body.charStream())) { jsonReader.beginObject(); while (jsonReader.hasNext()) { if (payloadName.equals(jsonReader.nextName())) { return adapter.read(jsonReader); } else { jsonReader.skipValue(); } } return null; } finally { body.close(); } }; }
From source file:io.plaidapp.data.api.DenvelopingConverter.java
License:Apache License
@Override public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {// www . j a v a2s . c om // This converter requires an annotation providing the name of the payload in the envelope; // if one is not supplied then return null to continue down the converter chain. final String payloadName = getPayloadName(annotations); if (payloadName == null) return null; final TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type)); return new Converter<ResponseBody, Object>() { @Override public Object convert(ResponseBody body) throws IOException { try (JsonReader jsonReader = gson.newJsonReader(body.charStream())) { jsonReader.beginObject(); while (jsonReader.hasNext()) { if (payloadName.equals(jsonReader.nextName())) { return adapter.read(jsonReader); } else { jsonReader.skipValue(); } } return null; } finally { body.close(); } } }; }
From source file:jp.pay.model.ExternalAccountTypeAdapterFactory.java
License:Open Source License
@SuppressWarnings("unchecked") public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { if (!ExternalAccount.class.isAssignableFrom(type.getRawType())) { return null; // this class only serializes 'ExternalAccount' and its subtypes }/*from w ww . j a v a2 s .co m*/ final String SOURCE_OBJECT_PROP = "object"; final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class); final TypeAdapter<ExternalAccount> externalAccountAdapter = gson.getDelegateAdapter(this, TypeToken.get(ExternalAccount.class)); final TypeAdapter<Card> cardAdapter = gson.getDelegateAdapter(this, TypeToken.get(Card.class)); TypeAdapter<ExternalAccount> result = new TypeAdapter<ExternalAccount>() { public void write(JsonWriter out, ExternalAccount value) throws IOException { // TODO: check instance of for correct writer externalAccountAdapter.write(out, value); } public ExternalAccount read(JsonReader in) throws IOException { JsonObject object = elementAdapter.read(in).getAsJsonObject(); String sourceObject = object.getAsJsonPrimitive(SOURCE_OBJECT_PROP).getAsString(); if (sourceObject.equals("card")) { return cardAdapter.fromJsonTree(object); } else { return externalAccountAdapter.fromJsonTree(object); } } }.nullSafe(); return (TypeAdapter<T>) result; }
From source file:me.albinmathew.celluloid.api.http.ItemTypeAdapterFactory.java
License:Apache License
@NonNull public <T> TypeAdapter<T> create(@NonNull Gson gson, final TypeToken<T> type) { final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class); return new TypeAdapter<T>() { public void write(JsonWriter out, T value) throws IOException { delegate.write(out, value);/* ww w . j av a2 s. c om*/ } public T read(JsonReader in) throws IOException { JsonElement jsonElement = elementAdapter.read(in); return delegate.fromJsonTree(jsonElement); } }.nullSafe(); }
From source file:mx.openpay.client.serialization.OpenpayTypeAdapterFactory.java
License:Apache License
public TypeAdapter<C> getClassAdapter(final Gson gson, final TypeToken<C> type) { final TypeAdapter<C> delegate = gson.getDelegateAdapter(this, type); final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class); return new TypeAdapter<C>() { @Override/*from w w w . j a v a 2s . c o m*/ public void write(final JsonWriter out, final C value) throws IOException { JsonElement tree = delegate.toJsonTree(value); OpenpayTypeAdapterFactory.this.beforeWrite(value, tree); elementAdapter.write(out, tree); } @Override public C read(final JsonReader in) throws IOException { JsonElement tree = elementAdapter.read(in); OpenpayTypeAdapterFactory.this.afterRead(tree); return delegate.fromJsonTree(tree); } }; }
From source file:org.arl.fjage.remote.ArrayAdapterFactory.java
License:BSD License
@SuppressWarnings("unchecked") public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { final Class<T> rawType = (Class<T>) type.getRawType(); if (!rawType.isArray()) return null; final Class<?> compType = rawType.getComponentType(); if (compType == null) return null; if (!compType.isPrimitive()) return null; if (!compType.equals(byte.class) && !compType.equals(int.class) && !compType.equals(short.class) && !compType.equals(long.class) && !compType.equals(float.class) && !compType.equals(double.class)) return null; final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); return new TypeAdapter<T>() { @Override//from w w w . jav a 2 s. co m public void write(JsonWriter out, T value) throws IOException { if (value == null) out.nullValue(); else { byte[] data; if (compType.equals(byte.class)) data = (byte[]) value; else { ByteBuffer buf = null; if (compType.equals(int.class)) { buf = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE * ((int[]) value).length) .order(ByteOrder.LITTLE_ENDIAN); buf.asIntBuffer().put((int[]) value); } else if (compType.equals(short.class)) { buf = ByteBuffer.allocate(Short.SIZE / Byte.SIZE * ((short[]) value).length) .order(ByteOrder.LITTLE_ENDIAN); buf.asShortBuffer().put((short[]) value); } else if (compType.equals(long.class)) { buf = ByteBuffer.allocate(Long.SIZE / Byte.SIZE * ((long[]) value).length) .order(ByteOrder.LITTLE_ENDIAN); buf.asLongBuffer().put((long[]) value); } else if (compType.equals(float.class)) { buf = ByteBuffer.allocate(Float.SIZE / Byte.SIZE * ((float[]) value).length) .order(ByteOrder.LITTLE_ENDIAN); buf.asFloatBuffer().put((float[]) value); } else if (compType.equals(double.class)) { buf = ByteBuffer.allocate(Double.SIZE / Byte.SIZE * ((double[]) value).length) .order(ByteOrder.LITTLE_ENDIAN); buf.asDoubleBuffer().put((double[]) value); } data = buf.array(); } if (bare) out.value(Base64.getEncoder().encodeToString(data)); else { out.beginObject(); out.name("clazz").value(rawType.getName()); out.name("data").value(Base64.getEncoder().encodeToString(data)); out.endObject(); } } } @Override public T read(JsonReader in) throws IOException { JsonToken tok = in.peek(); if (tok == JsonToken.NULL) { in.nextNull(); return null; } if (tok == JsonToken.STRING) return decodeString(in.nextString()); if (tok == JsonToken.BEGIN_ARRAY) return delegate.read(in); if (tok != JsonToken.BEGIN_OBJECT) return null; T rv = null; in.beginObject(); while (in.hasNext()) { String name = in.nextName(); if (name.equals("data")) rv = decodeString(in.nextString()); else in.skipValue(); } in.endObject(); return rv; } private T decodeString(String s) { byte[] data = Base64.getDecoder().decode(s); if (compType.equals(byte.class)) return (T) data; ByteBuffer buf = ByteBuffer.wrap(data); if (compType.equals(int.class)) { IntBuffer buf2 = ByteBuffer.wrap(Base64.getDecoder().decode(s)).order(ByteOrder.LITTLE_ENDIAN) .asIntBuffer(); int[] array = new int[buf2.limit()]; buf2.get(array); return (T) array; } if (compType.equals(short.class)) { ShortBuffer buf2 = ByteBuffer.wrap(Base64.getDecoder().decode(s)).order(ByteOrder.LITTLE_ENDIAN) .asShortBuffer(); short[] array = new short[buf2.limit()]; buf2.get(array); return (T) array; } if (compType.equals(long.class)) { LongBuffer buf2 = ByteBuffer.wrap(Base64.getDecoder().decode(s)).order(ByteOrder.LITTLE_ENDIAN) .asLongBuffer(); long[] array = new long[buf2.limit()]; buf2.get(array); return (T) array; } if (compType.equals(float.class)) { FloatBuffer buf2 = ByteBuffer.wrap(Base64.getDecoder().decode(s)).order(ByteOrder.LITTLE_ENDIAN) .asFloatBuffer(); float[] array = new float[buf2.limit()]; buf2.get(array); return (T) array; } if (compType.equals(double.class)) { DoubleBuffer buf2 = ByteBuffer.wrap(Base64.getDecoder().decode(s)) .order(ByteOrder.LITTLE_ENDIAN).asDoubleBuffer(); double[] array = new double[buf2.limit()]; buf2.get(array); return (T) array; } return null; } }; }
From source file:org.arl.fjage.remote.GenericValueAdapterFactory.java
License:BSD License
public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) { final Class<T> rawType = (Class<T>) type.getRawType(); if (!rawType.equals(GenericValue.class)) return null; final GenericValueAdapterFactory parent = this; return new TypeAdapter<T>() { @Override// w w w .ja v a 2 s . co m public void write(JsonWriter out, T value) throws IOException { if (value == null) { out.nullValue(); return; } Class type = ((GenericValue) value).getType(); if (type == null) { out.nullValue(); return; } if (Number.class.isAssignableFrom(type)) out.value((Number) ((GenericValue) value).getValue()); else if (type.equals(String.class)) out.value((String) ((GenericValue) value).getValue()); else if (type.equals(Boolean.class)) out.value((Boolean) ((GenericValue) value).getValue()); else { out.beginObject(); out.name("clazz").value(type.getName()); out.name("data"); TypeAdapter delegate = gson.getAdapter(TypeToken.get(type)); Object v = ((GenericValue) value).getValue(); delegate.write(out, v); out.endObject(); } } @Override public T read(JsonReader in) throws IOException { JsonToken tok = in.peek(); if (tok == JsonToken.NULL) { in.nextNull(); return null; } if (tok == JsonToken.NUMBER) { String s = in.nextString(); try { if (s.contains(".")) return (T) new GenericValue(Double.parseDouble(s)); else return (T) new GenericValue(Long.parseLong(s)); } catch (NumberFormatException ex) { return (T) new GenericValue(null); } } if (tok == JsonToken.STRING) return (T) new GenericValue(in.nextString()); if (tok == JsonToken.BOOLEAN) return (T) new GenericValue(in.nextBoolean()); if (tok != JsonToken.BEGIN_OBJECT) return null; TypeToken tt = null; GenericValue rv = null; in.beginObject(); while (in.hasNext()) { String name = in.nextName(); if (name.equals("clazz")) { try { Class<?> cls = Class.forName(in.nextString()); tt = TypeToken.get(cls); } catch (Exception ex) { // do nothing } } else if (name.equals("data") && tt != null) { TypeAdapter delegate = gson.getAdapter(tt); rv = new GenericValue(delegate.read(in)); } else in.skipValue(); } in.endObject(); return (T) rv; } }; }
From source file:org.arl.fjage.remote.MessageAdapterFactory.java
License:BSD License
@SuppressWarnings("unchecked") public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) { final Class<T> rawType = (Class<T>) type.getRawType(); if (!Message.class.isAssignableFrom(rawType)) return null; final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); final TypeAdapter<Performative> perfDelegate = gson.getAdapter(TypeToken.get(Performative.class)); final TypeAdapter<AgentID> aidDelegate = gson.getAdapter(TypeToken.get(AgentID.class)); final TypeAdapter<GenericValue> gvDelegate = gson.getAdapter(TypeToken.get(GenericValue.class)); final MessageAdapterFactory parent = this; return new TypeAdapter<T>() { @Override//from w w w . ja v a2 s .com public void write(JsonWriter out, T value) throws IOException { if (value == null) out.nullValue(); else { out.beginObject(); out.name("clazz").value(value.getClass().getName()); out.name("data"); if (value instanceof GenericMessage) { GenericMessage msg = (GenericMessage) value; out.beginObject(); out.name("msgID").value(msg.getMessageID()); out.name("inReplyTo").value(msg.getInReplyTo()); out.name("perf"); perfDelegate.write(out, msg.getPerformative()); out.name("recipient"); aidDelegate.write(out, msg.getRecipient()); out.name("sender"); aidDelegate.write(out, msg.getSender()); out.name("map"); delegate.write(out, value); out.endObject(); } else delegate.write(out, value); out.endObject(); } } @Override public T read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } T rv = null; Class<?> cls = null; in.beginObject(); while (in.hasNext()) { String name = in.nextName(); if (name.equals("clazz")) { String className = in.nextString(); try { cls = classloader != null ? Class.forName(className, true, classloader) : Class.forName(className); } catch (Exception ex) { // do nothing } } else if (name.equals("data")) { if (cls == null) rv = delegate.read(in); else if (cls.equals(GenericMessage.class)) { GenericMessage msg = new GenericMessage(); in.beginObject(); while (in.hasNext()) { String fname = in.nextName(); if (fname.equals("msgID")) msg.setMessageID(in.nextString()); else if (fname.equals("inReplyTo")) msg.setInReplyTo(in.nextString()); else if (fname.equals("perf")) msg.setPerformative(perfDelegate.read(in)); else if (fname.equals("recipient")) msg.setRecipient(aidDelegate.read(in)); else if (fname.equals("sender")) msg.setSender(aidDelegate.read(in)); else if (fname.equals("map")) { in.beginObject(); while (in.hasNext()) { String key = in.nextName(); GenericValue value = gvDelegate.read(in); msg.put(key, value); } in.endObject(); } else in.skipValue(); } in.endObject(); rv = (T) msg; } else { TypeAdapter<?> delegate1 = gson.getDelegateAdapter(parent, TypeToken.get(cls)); rv = (T) delegate1.read(in); } } else in.skipValue(); } in.endObject(); return rv; } }; }
From source file:org.eclipse.lsp4j.jsonrpc.json.adapters.MessageTypeAdapter.java
License:Open Source License
/** * Convert the json input into the result object corresponding to the call made * by id.// w ww. j ava 2s . c o m * * If the id is not known until after parsing, call * {@link #parseResult(Object, String)} on the return value of this call for a * second chance conversion. * * @param in * json input to read from * @param id * id of request message this is in response to * @return correctly typed object if the correct expected type can be * determined, or a JsonElement representing the result */ protected Object parseResult(JsonReader in, String id) throws JsonIOException, JsonSyntaxException { Type type = null; MethodProvider methodProvider = handler.getMethodProvider(); if (methodProvider != null && id != null) { String resolvedMethod = methodProvider.resolveMethod(id); if (resolvedMethod != null) { JsonRpcMethod jsonRpcMethod = handler.getJsonRpcMethod(resolvedMethod); if (jsonRpcMethod != null) { type = jsonRpcMethod.getReturnType(); if (jsonRpcMethod.getReturnTypeAdapterFactory() != null) { TypeAdapter<?> typeAdapter = jsonRpcMethod.getReturnTypeAdapterFactory().create(gson, TypeToken.get(type)); try { if (typeAdapter != null) return typeAdapter.read(in); } catch (IOException exception) { throw new JsonIOException(exception); } } } } } return fromJson(in, type); }
From source file:org.eclipse.recommenders.utils.gson.MultisetTypeAdapterFactory.java
License:Open Source License
private <E> TypeAdapter<Multiset<E>> newMultisetAdapter(final TypeAdapter<E> elementAdapter) { return new TypeAdapter<Multiset<E>>() { public void write(JsonWriter out, Multiset<E> multiset) throws IOException { if (multiset == null) { out.nullValue();/*from ww w . j a va2 s . c om*/ return; } out.beginArray(); for (Entry<E> entry : multiset.entrySet()) { out.beginObject(); out.name("id"); elementAdapter.write(out, entry.getElement()); out.name("count"); out.value(entry.getCount()); out.endObject(); } out.endArray(); } public Multiset<E> read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } Multiset<E> result = LinkedHashMultiset.create(); in.beginArray(); while (in.hasNext()) { in.beginObject(); in.nextName(); // "id" E element = elementAdapter.read(in); in.nextName(); // "count" int count = in.nextInt(); result.add(element, count); in.endObject(); } in.endArray(); return result; } }; }