From a83a9b79e43fa3fcc6988e0a48bb32341ec1b68c Mon Sep 17 00:00:00 2001 From: Eric Cochran Date: Fri, 15 Feb 2019 17:09:50 -0800 Subject: [PATCH] Use peekJson in the DefaultOnDataMismatchAdapter example. (#809) --- .../recipes/DefaultOnDataMismatchAdapter.java | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/examples/src/main/java/com/squareup/moshi/recipes/DefaultOnDataMismatchAdapter.java b/examples/src/main/java/com/squareup/moshi/recipes/DefaultOnDataMismatchAdapter.java index 19a5324..9a2e9fb 100644 --- a/examples/src/main/java/com/squareup/moshi/recipes/DefaultOnDataMismatchAdapter.java +++ b/examples/src/main/java/com/squareup/moshi/recipes/DefaultOnDataMismatchAdapter.java @@ -36,17 +36,20 @@ public final class DefaultOnDataMismatchAdapter extends JsonAdapter { } @Override public T fromJson(JsonReader reader) throws IOException { - // Read the value first so that the reader will be in a known state even if there's an - // exception. Otherwise it may be awkward to recover: it might be between calls to - // beginObject() and endObject() for example. - Object jsonValue = reader.readJsonValue(); - - // Use the delegate to convert the JSON value to the target type. + // Use a peeked reader to leave the reader in a known state even if there's an exception. + JsonReader peeked = reader.peekJson(); + T result; try { - return delegate.fromJsonValue(jsonValue); + // Attempt to decode to the target type with the peeked reader. + result = delegate.fromJson(peeked); } catch (JsonDataException e) { - return defaultValue; + result = defaultValue; + } finally { + peeked.close(); } + // Skip the value back on the reader, no matter the state of the peeked reader. + reader.skipValue(); + return result; } @Override public void toJson(JsonWriter writer, T value) throws IOException {