Java Code Examples for com.google.gson.TypeAdapter#read()
The following examples show how to use
com.google.gson.TypeAdapter#read() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GsonPostProcessEnablingTypeFactory.java From intellij-spring-assistant with MIT License | 6 votes |
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { TypeAdapter<T> delegateAdapter = gson.getDelegateAdapter(this, typeToken); return new TypeAdapter<T>() { @Override public void write(JsonWriter jsonWriter, T value) throws IOException { delegateAdapter.write(jsonWriter, value); } @Override public T read(JsonReader jsonReader) throws IOException { T obj = delegateAdapter.read(jsonReader); if (obj instanceof GsonPostProcessable) { GsonPostProcessable.class.cast(obj).doOnGsonDeserialization(); } return obj; } }; }
Example 2
Source File: JavaTimeTest.java From immutables with Apache License 2.0 | 6 votes |
@Test public void localDate() throws IOException { long epoch = System.currentTimeMillis(); LocalDate now = Instant.ofEpochMilli(epoch).atOffset(ZoneOffset.UTC).toLocalDate(); TypeAdapter<LocalDate> adapter = gson.getAdapter(LocalDate.class); // read LocalDate date = adapter.read(Jsons.readerAt(new BsonDateTime(epoch))); check(date).is(now); // write BsonValue bson = writeAndReadBson(now); check(bson.getBsonType()).is(BsonType.DATE_TIME); check(Instant.ofEpochMilli(bson.asDateTime().getValue()).atOffset(ZoneOffset.UTC).toLocalDate()).is(now); }
Example 3
Source File: TypeAdapters.java From gson with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { if (typeToken.getRawType() != Timestamp.class) { return null; } final TypeAdapter<Date> dateTypeAdapter = gson.getAdapter(Date.class); return (TypeAdapter<T>) new TypeAdapter<Timestamp>() { @Override public Timestamp read(JsonReader in) throws IOException { Date date = dateTypeAdapter.read(in); return date != null ? new Timestamp(date.getTime()) : null; } @Override public void write(JsonWriter out, Timestamp value) throws IOException { dateTypeAdapter.write(out, value); } }; }
Example 4
Source File: DtoFactory.java From che with Eclipse Public License 2.0 | 6 votes |
@Override @SuppressWarnings("unchecked") public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { if (!matchedClass.isAssignableFrom(type.getRawType())) { return null; } TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); return new TypeAdapter<T>() { @Override public void write(JsonWriter out, T value) throws IOException { delegate.write(out, value != null ? value : (T) defaultValue); } @Override public T read(JsonReader in) throws IOException { return delegate.read(in); } }; }
Example 5
Source File: ExpectedSubtypesAdapter.java From immutables with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") @Override public T read(JsonReader in) throws IOException { List<Exception> exceptions = new ArrayList<>(subtypes.length); ReaderSupplier readerSupplier = readForSupplier(in); for (TypeAdapter<?> typeAdapter : adapters) { try { return (T) typeAdapter.read(readerSupplier.create()); } catch (Exception ex) { exceptions.add(ex); } } JsonParseException failure = new JsonParseException( String.format( "Cannot parse %s with following subtypes: %s", type, Arrays.toString(subtypes))); for (Exception exception : exceptions) { failure.addSuppressed(exception); } throw failure; }
Example 6
Source File: SafeListAdapter.java From twitter-kit-android with Apache License 2.0 | 6 votes |
@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 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; } }; }
Example 7
Source File: MessageTypeAdapter.java From lsp4j with Eclipse Public License 2.0 | 6 votes |
/** * Convert the json input into the result object corresponding to the call made * by id. * * 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); }
Example 8
Source File: TypeAdapters.java From framework with GNU Affero General Public License v3.0 | 6 votes |
@SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { if (typeToken.getRawType() != Timestamp.class) { return null; } final TypeAdapter<Date> dateTypeAdapter = gson.getAdapter(Date.class); return (TypeAdapter<T>) new TypeAdapter<Timestamp>() { @Override public Timestamp read(JsonReader in) throws IOException { Date date = dateTypeAdapter.read(in); return date != null ? new Timestamp(date.getTime()) : null; } @Override public void write(JsonWriter out, Timestamp value) throws IOException { dateTypeAdapter.write(out, value); } }; }
Example 9
Source File: JavaTimeTest.java From immutables with Apache License 2.0 | 6 votes |
@Test public void instant() throws IOException { Instant now = Instant.now(); long epoch = now.toEpochMilli(); TypeAdapter<Instant> adapter = gson.getAdapter(Instant.class); // read Instant date = adapter.read(Jsons.readerAt(new BsonDateTime(epoch))); check(date).is(now); // write BsonValue bson = writeAndReadBson(now); check(bson.getBsonType()).is(BsonType.DATE_TIME); check(Instant.ofEpochMilli(bson.asDateTime().getValue())).is(now); }
Example 10
Source File: Adapter.java From last.fm-api with MIT License | 6 votes |
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); } public T read(JsonReader in) throws IOException { T obj = delegate.read(in); if (obj instanceof PostProcessable) { ((PostProcessable)obj).postProcess(); } return obj; } }; }
Example 11
Source File: TypeAdapters.java From letv with Apache License 2.0 | 6 votes |
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { if (typeToken.getRawType() != Timestamp.class) { return null; } final TypeAdapter<Date> dateTypeAdapter = gson.getAdapter(Date.class); return new TypeAdapter<Timestamp>() { public Timestamp read(JsonReader in) throws IOException { Date date = (Date) dateTypeAdapter.read(in); return date != null ? new Timestamp(date.getTime()) : null; } public void write(JsonWriter out, Timestamp value) throws IOException { dateTypeAdapter.write(out, value); } }; }
Example 12
Source File: Adapter.java From SoundCloud-API with MIT License | 6 votes |
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); } public T read(JsonReader in) throws IOException { T obj = delegate.read(in); if (obj instanceof PostProcessable) { ((PostProcessable)obj).postProcess(); } return obj; } }; }
Example 13
Source File: DenvelopingConverter.java From android-proguards with Apache License 2.0 | 5 votes |
@Override public Converter<ResponseBody, ?> responseBodyConverter( Type type, Annotation[] annotations, Retrofit retrofit) { // 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(); } } }; }
Example 14
Source File: DataTypeAdapterFactory.java From mvvm-starter with MIT License | 5 votes |
@Override public <T> TypeAdapter<T> create (Gson gson, TypeToken<T> type) { final TypeAdapter<T> lDelegate = gson.getDelegateAdapter(this, type); final TypeAdapter<JsonElement> lElementAdapter = gson.getAdapter(JsonElement.class); return new TypeAdapter<T>() { @Override public void write (JsonWriter out, T value) throws IOException { lDelegate.write(out, value); } @Override public T read (JsonReader in) throws IOException { JsonElement lElement = lElementAdapter.read(in); if (lElement.isJsonObject()) { JsonObject lObject = lElement.getAsJsonObject(); if (lObject.has("data")) { lElement = lObject.get("data"); } } return lDelegate.fromJsonTree(lElement); } }; }
Example 15
Source File: PostTypeAdapterFactory.java From quill with MIT License | 5 votes |
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { @SuppressWarnings("unchecked") Class<T> rawType = (Class<T>) type.getRawType(); if (rawType != Post.class) { return null; } final TypeAdapter delegate = gson.getDelegateAdapter(this, type); //noinspection unchecked return (TypeAdapter<T>) new TypeAdapter<Post>() { @Override public void write(JsonWriter out, Post value) throws IOException { //noinspection unchecked delegate.write(out, value); } @Override public Post read(JsonReader in) throws IOException { Post post = (Post) delegate.read(in); // Empty posts imported from Ghost 0.11.x have mobiledoc == null, which is incorrect // but we do need to handle it. Drafts created in Ghost 1.0 on the other hand, do // have mobiledoc set to a valid, empty mobiledoc document. if (post.getMobiledoc() != null && !post.getMobiledoc().isEmpty()) { // Post JSON example: // { // "mobiledoc": "{\"version\": \"0.3.1\", ... }", // ... // } post.setMarkdown(GhostApiUtils.mobiledocToMarkdown(post.getMobiledoc())); } else { post.setMarkdown(""); } return post; } }; }
Example 16
Source File: OptionalTypeAdapterFactory.java From plaid-java with MIT License | 5 votes |
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { if (!Optional.class.isAssignableFrom(type.getRawType())) { return null; } final TypeAdapter delegateAdapter = gson.getAdapter(TypeToken.get(((ParameterizedType) type.getType()).getActualTypeArguments()[0])); return new TypeAdapter<T>() { @Override @SuppressWarnings({"unchecked", "rawtypes"}) public void write(JsonWriter out, T value) throws IOException { if (((Optional) value).isPresent()) { delegateAdapter.write(out, ((Optional) value).get()); } else { out.nullValue(); } } @Override @SuppressWarnings("unchecked") public T read(JsonReader in) throws IOException { Object readObject = delegateAdapter.read(in); if (readObject == null) { return (T) Optional.empty(); } else { return (T) Optional.of(readObject); } } }; }
Example 17
Source File: GsonResponseBodyConverter.java From proteus with Apache License 2.0 | 5 votes |
@Override public T convert(ResponseBody value) throws IOException { TypeAdapter<T> adapter = getAdapter(); JsonReader jsonReader = gson.newJsonReader(value.charStream()); jsonReader.setLenient(true); try { return adapter.read(jsonReader); } finally { value.close(); } }
Example 18
Source File: BaseGeometryTypeAdapter.java From mapbox-java with MIT License | 4 votes |
public CoordinateContainer<T> readCoordinateContainer(JsonReader jsonReader) throws IOException { if (jsonReader.peek() == JsonToken.NULL) { jsonReader.nextNull(); return null; } jsonReader.beginObject(); String type = null; BoundingBox bbox = null; T coordinates = null; while (jsonReader.hasNext()) { String name = jsonReader.nextName(); if (jsonReader.peek() == JsonToken.NULL) { jsonReader.nextNull(); continue; } switch (name) { case "type": TypeAdapter<String> stringAdapter = this.stringAdapter; if (stringAdapter == null) { stringAdapter = gson.getAdapter(String.class); this.stringAdapter = stringAdapter; } type = stringAdapter.read(jsonReader); break; case "bbox": TypeAdapter<BoundingBox> boundingBoxAdapter = this.boundingBoxAdapter; if (boundingBoxAdapter == null) { boundingBoxAdapter = gson.getAdapter(BoundingBox.class); this.boundingBoxAdapter = boundingBoxAdapter; } bbox = boundingBoxAdapter.read(jsonReader); break; case "coordinates": TypeAdapter<T> coordinatesAdapter = this.coordinatesAdapter; if (coordinatesAdapter == null) { throw new GeoJsonException("Coordinates type adapter is null"); } coordinates = coordinatesAdapter.read(jsonReader); break; default: jsonReader.skipValue(); } } jsonReader.endObject(); return createCoordinateContainer(type, bbox, coordinates); }
Example 19
Source File: CustomTypeAdapterFactory.java From yawp with MIT License | 4 votes |
/** * Override this to define how this is deserialized in {@code deserialize} to * its type. */ protected T read(JsonReader in, TypeAdapter<JsonElement> elementAdapter, TypeAdapter<T> delegate) throws IOException { JsonElement tree = elementAdapter.read(in); afterRead(tree); return delegate.fromJsonTree(tree); }
Example 20
Source File: NullableTypeAdapterFactory.java From v20-java with MIT License | 4 votes |
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { if (type.getRawType() != NullableType.class) { return null; } if (getBaseType(type.getType()) != this.containedClass) { return null; } final TypeAdapter<C> delegate = gson.getDelegateAdapter(this, TypeToken.get(this.containedClass)); return new TypeAdapter<T>() { @SuppressWarnings("unchecked") @Override public void write(JsonWriter out, T value) throws IOException { if (value == null || ! ((NullableType<C>) value).isSet()) { out.nullValue(); } else if (((NullableType<C>) value).getValue() == null) { boolean oldSerializeNulls = out.getSerializeNulls(); out.setSerializeNulls(true); out.nullValue(); out.setSerializeNulls(oldSerializeNulls); } else { try { delegate.write(out, (C) (((NullableType<C>) value).getValue())); } catch (IllegalArgumentException e) { throw new IOException(e); } } } @SuppressWarnings("unchecked") @Override public T read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return (T) new NullableType<C>(); } else { return (T) new NullableType<C>(delegate.read(in)); } } }; }