Use peekJson in the DefaultOnDataMismatchAdapter example. (#809)
This commit is contained in:
parent
d843950731
commit
a83a9b79e4
1 changed files with 11 additions and 8 deletions
|
@ -36,17 +36,20 @@ public final class DefaultOnDataMismatchAdapter<T> extends JsonAdapter<T> {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override public T fromJson(JsonReader reader) throws IOException {
|
@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
|
// Use a peeked reader to leave the reader in a known state even if there's an exception.
|
||||||
// exception. Otherwise it may be awkward to recover: it might be between calls to
|
JsonReader peeked = reader.peekJson();
|
||||||
// beginObject() and endObject() for example.
|
T result;
|
||||||
Object jsonValue = reader.readJsonValue();
|
|
||||||
|
|
||||||
// Use the delegate to convert the JSON value to the target type.
|
|
||||||
try {
|
try {
|
||||||
return delegate.fromJsonValue(jsonValue);
|
// Attempt to decode to the target type with the peeked reader.
|
||||||
|
result = delegate.fromJson(peeked);
|
||||||
} catch (JsonDataException e) {
|
} 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 {
|
@Override public void toJson(JsonWriter writer, T value) throws IOException {
|
||||||
|
|
Loading…
Reference in a new issue