Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 28 additions & 14 deletions gson/src/main/java/com/google/gson/Gson.java
Original file line number Diff line number Diff line change
Expand Up @@ -841,7 +841,8 @@ public JsonReader newJsonReader(Reader reader) {
* @param json the string from which the object is to be deserialized
* @param classOfT the class of T
* @return an object of type T from the string. Returns {@code null} if {@code json} is {@code
* null} or if {@code json} is empty.
* null} or if {@code json} is empty (unless this {@code Gson} instance uses {@link
* Strictness#STRICT}; see {@link GsonBuilder#setStrictness(Strictness)}).
* @throws JsonSyntaxException if json is not a valid representation for an object of type
* classOfT
* @see #fromJson(Reader, Class)
Expand Down Expand Up @@ -869,7 +870,8 @@ public <T> T fromJson(String json, Class<T> classOfT) throws JsonSyntaxException
* @param json the string from which the object is to be deserialized
* @param typeOfT The specific genericized type of src
* @return an object of type T from the string. Returns {@code null} if {@code json} is {@code
* null} or if {@code json} is empty.
* null} or if {@code json} is empty (unless this {@code Gson} instance uses {@link
* Strictness#STRICT}; see {@link GsonBuilder#setStrictness(Strictness)}).
* @throws JsonSyntaxException if json is not a valid representation for an object of type typeOfT
* @see #fromJson(Reader, Type)
* @see #fromJson(String, Class)
Expand Down Expand Up @@ -899,7 +901,8 @@ public <T> T fromJson(String json, Type typeOfT) throws JsonSyntaxException {
* </pre>
*
* @return an object of type T from the string. Returns {@code null} if {@code json} is {@code
* null} or if {@code json} is empty.
* null} or if {@code json} is empty (unless this {@code Gson} instance uses {@link
* Strictness#STRICT}; see {@link GsonBuilder#setStrictness(Strictness)}).
* @throws JsonSyntaxException if json is not a valid representation for an object of the type
* typeOfT
* @see #fromJson(Reader, TypeToken)
Expand Down Expand Up @@ -930,7 +933,9 @@ public <T> T fromJson(String json, TypeToken<T> typeOfT) throws JsonSyntaxExcept
* @param <T> the type of the desired object
* @param json the reader producing the JSON from which the object is to be deserialized.
* @param classOfT the class of T
* @return an object of type T from the Reader. Returns {@code null} if {@code json} is at EOF.
* @return an object of type T from the Reader. Returns {@code null} if {@code json} is at EOF
* (unless this {@code Gson} instance uses {@link Strictness#STRICT}; see {@link
* GsonBuilder#setStrictness(Strictness)}).
* @throws JsonIOException if there was a problem reading from the Reader
* @throws JsonSyntaxException if json is not a valid representation for an object of type typeOfT
* @since 1.2
Expand Down Expand Up @@ -959,7 +964,9 @@ public <T> T fromJson(Reader json, Class<T> classOfT)
* @param <T> the type of the desired object
* @param json the reader producing JSON from which the object is to be deserialized
* @param typeOfT The specific genericized type of src
* @return an object of type T from the Reader. Returns {@code null} if {@code json} is at EOF.
* @return an object of type T from the Reader. Returns {@code null} if {@code json} is at EOF
* (unless this {@code Gson} instance uses {@link Strictness#STRICT}; see {@link
* GsonBuilder#setStrictness(Strictness)}).
* @throws JsonIOException if there was a problem reading from the Reader
* @throws JsonSyntaxException if json is not a valid representation for an object of type typeOfT
* @since 1.2
Expand Down Expand Up @@ -990,7 +997,9 @@ public <T> T fromJson(Reader json, Type typeOfT) throws JsonIOException, JsonSyn
* new TypeToken&lt;Collection&lt;Foo&gt;&gt;(){}
* </pre>
*
* @return an object of type T from the Reader. Returns {@code null} if {@code json} is at EOF.
* @return an object of type T from the Reader. Returns {@code null} if {@code json} is at EOF
* (unless this {@code Gson} instance uses {@link Strictness#STRICT}; see {@link
* GsonBuilder#setStrictness(Strictness)}).
* @throws JsonIOException if there was a problem reading from the Reader
* @throws JsonSyntaxException if json is not a valid representation for an object of type of
* typeOfT
Expand All @@ -1012,7 +1021,8 @@ public <T> T fromJson(Reader json, TypeToken<T> typeOfT)

/**
* Reads the next JSON value from {@code reader} and converts it to an object of type {@code
* typeOfT}. Returns {@code null}, if the {@code reader} is at EOF.
* typeOfT}. Returns {@code null} if the {@code reader} is at EOF, unless the effective strictness
* (see below) is {@link Strictness#STRICT}, in which case {@link JsonSyntaxException} is thrown.
*
* <p>Since {@code Type} is not parameterized by T, this method is not type-safe and should be
* used carefully. If you are creating the {@code Type} from a {@link TypeToken}, prefer using
Expand All @@ -1036,7 +1046,8 @@ public <T> T fromJson(Reader json, TypeToken<T> typeOfT)
* @param reader the reader whose next JSON value should be deserialized
* @param typeOfT The specific genericized type of src
* @return an object of type T from the JsonReader. Returns {@code null} if {@code reader} is at
* EOF.
* EOF, unless the effective strictness (see above) is {@link Strictness#STRICT}, in which
* case {@link JsonSyntaxException} is thrown.
* @throws JsonIOException if there was a problem reading from the JsonReader
* @throws JsonSyntaxException if json is not a valid representation for an object of type typeOfT
* @see #fromJson(Reader, Type)
Expand All @@ -1050,9 +1061,11 @@ public <T> T fromJson(JsonReader reader, Type typeOfT)

/**
* Reads the next JSON value from {@code reader} and converts it to an object of type {@code
* typeOfT}. Returns {@code null}, if the {@code reader} is at EOF. This method is useful if the
* specified object is a generic type. For non-generic objects, {@link #fromJson(JsonReader,
* Type)} can be called, or {@link TypeToken#get(Class)} can be used to create the type token.
* typeOfT}. Returns {@code null} if the {@code reader} is at EOF, unless the effective strictness
* (see below) is {@link Strictness#STRICT}, in which case {@link JsonSyntaxException} is thrown.
* This method is useful if the specified object is a generic type. For non-generic objects,
* {@link #fromJson(JsonReader, Type)} can be called, or {@link TypeToken#get(Class)} can be used
* to create the type token.
*
* <p>Unlike the other {@code fromJson} methods, no exception is thrown if the JSON data has
* multiple top-level JSON elements, or if there is trailing data.
Expand All @@ -1076,7 +1089,8 @@ public <T> T fromJson(JsonReader reader, Type typeOfT)
* </pre>
*
* @return an object of type T from the JsonReader. Returns {@code null} if {@code reader} is at
* EOF.
* EOF, unless the effective strictness (see above) is {@link Strictness#STRICT}, in which
* case {@link JsonSyntaxException} is thrown.
* @throws JsonIOException if there was a problem reading from the JsonReader
* @throws JsonSyntaxException if json is not a valid representation for an object of the type
* typeOfT
Expand Down Expand Up @@ -1116,9 +1130,9 @@ public <T> T fromJson(JsonReader reader, TypeToken<T> typeOfT)
} catch (EOFException e) {
/*
* For compatibility with Gson 1.5 and earlier, we return null for empty
* documents instead of throwing.
* documents instead of throwing, unless the reader's strictness is Strictness.STRICT.
*/
if (isEmpty) {
if (isEmpty && reader.getStrictness() != Strictness.STRICT) {
return null;
}
throw new JsonSyntaxException(e);
Expand Down
3 changes: 3 additions & 0 deletions gson/src/main/java/com/google/gson/GsonBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -590,6 +590,9 @@ public GsonBuilder setLenient() {
* <p>This changes how strict the <a href="https://www.ietf.org/rfc/rfc8259.txt">RFC 8259 JSON
* specification</a> is enforced when parsing or writing JSON. For details on this, refer to
* {@link JsonReader#setStrictness(Strictness)} and {@link JsonWriter#setStrictness(Strictness)}.
* Additionally, when {@link Strictness#STRICT} is set, empty JSON documents cause {@link
* Gson#fromJson(String, Class) Gson.fromJson} to throw {@link JsonSyntaxException} instead of
* returning {@code null}.
*
* @param strictness the new strictness mode. May not be {@code null}.
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern.
Expand Down
7 changes: 4 additions & 3 deletions gson/src/main/java/com/google/gson/JsonParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -125,9 +125,10 @@ public static JsonElement parseReader(Reader reader) throws JsonIOException, Jso
* there is trailing data.
*
* <p>If the {@linkplain JsonReader#getStrictness() strictness of the reader} is {@link
* Strictness#STRICT}, that strictness will be used for parsing. Otherwise the strictness will be
* temporarily changed to {@link Strictness#LENIENT} and will be restored once this method
* returns.
* Strictness#STRICT}, that strictness will be used for parsing, and an empty document will throw
* {@link JsonSyntaxException} instead of returning {@link JsonNull#INSTANCE}. Otherwise the
* strictness will be temporarily changed to {@link Strictness#LENIENT} and will be restored once
* this method returns.
*
* @throws JsonParseException if there is an IOException or if the specified text is not valid
* JSON
Expand Down
5 changes: 3 additions & 2 deletions gson/src/main/java/com/google/gson/internal/Streams.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import com.google.gson.JsonNull;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;
import com.google.gson.Strictness;
import com.google.gson.internal.bind.JsonElementTypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
Expand Down Expand Up @@ -49,9 +50,9 @@ public static JsonElement parse(JsonReader reader) throws JsonParseException {
} catch (EOFException e) {
/*
* For compatibility with Gson 1.5 and earlier, we return a JsonNull for
* empty documents instead of throwing.
* empty documents instead of throwing, unless the reader's strictness is Strictness.STRICT.
*/
if (isEmpty) {
if (isEmpty && reader.getStrictness() != Strictness.STRICT) {
return JsonNull.INSTANCE;
}
// The stream ended prematurely so it is likely a syntax error.
Expand Down
156 changes: 156 additions & 0 deletions gson/src/test/java/com/google/gson/GsonTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,21 @@
package com.google.gson;

import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.assertThrows;

import com.google.gson.Gson.FutureTypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.internal.Excluder;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.google.gson.stream.MalformedJsonException;
import java.io.EOFException;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.Type;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
Expand Down Expand Up @@ -623,6 +627,158 @@ private static void assertCustomGson(Gson gson) {
assertThat(customClass3.s).isEqualTo("custom-instance");
}

@Test
public void testFromJsonEmptyDocumentStrictness() {
String[][] emptyInputs = {
{"empty", ""},
{"space", " "},
{"whitespace", "\t\r\n"},
{"BOM", "\uFEFF"},
};
Gson strictGson = new GsonBuilder().setStrictness(Strictness.STRICT).create();
Gson defaultGson = new Gson();
Gson legacyStrictGson = new GsonBuilder().setStrictness(Strictness.LEGACY_STRICT).create();
Gson lenientGson = new GsonBuilder().setStrictness(Strictness.LENIENT).create();
TypeToken<Object> objectType = TypeToken.get(Object.class);

assertThat(strictGson.fromJson((String) null, Object.class)).isNull();

JsonSyntaxException jsonElementException =
assertThrows(JsonSyntaxException.class, () -> strictGson.fromJson("", JsonElement.class));
assertThat(jsonElementException).hasCauseThat().isInstanceOf(EOFException.class);
assertThat(jsonElementException)
.hasCauseThat()
.hasMessageThat()
.isEqualTo("End of input at line 1 column 1 path $");

for (String[] entry : emptyInputs) {
String label = entry[0];
String input = entry[1];

JsonSyntaxException e1 =
assertThrows(JsonSyntaxException.class, () -> strictGson.fromJson(input, Object.class));
assertWithMessage("case: %s", label).that(e1).hasCauseThat().isInstanceOf(EOFException.class);
assertWithMessage("case: %s", label)
.that(e1)
.hasCauseThat()
.hasMessageThat()
.startsWith("End of input at line ");

StringReader stringReader = new StringReader(input);
JsonSyntaxException e2 =
assertThrows(
JsonSyntaxException.class, () -> strictGson.fromJson(stringReader, Object.class));
assertWithMessage("case: %s", label).that(e2).hasCauseThat().isInstanceOf(EOFException.class);

JsonReader strictReader = new JsonReader(new StringReader(input));
strictReader.setStrictness(Strictness.STRICT);
JsonSyntaxException e3 =
assertThrows(
JsonSyntaxException.class, () -> defaultGson.fromJson(strictReader, objectType));
assertWithMessage("case: %s", label).that(e3).hasCauseThat().isInstanceOf(EOFException.class);
assertThat(strictReader.getStrictness()).isEqualTo(Strictness.STRICT);

JsonReader lenientReader = new JsonReader(new StringReader(input));
lenientReader.setStrictness(Strictness.LENIENT);
JsonSyntaxException e4 =
assertThrows(
JsonSyntaxException.class, () -> strictGson.fromJson(lenientReader, objectType));
assertWithMessage("case: %s", label).that(e4).hasCauseThat().isInstanceOf(EOFException.class);
assertThat(lenientReader.getStrictness()).isEqualTo(Strictness.LENIENT);

// Explicitly non-STRICT Gson overrides a STRICT JsonReader and returns null
JsonReader overriddenByLenient = new JsonReader(new StringReader(input));
overriddenByLenient.setStrictness(Strictness.STRICT);
assertWithMessage("case: %s", label)
.that(lenientGson.fromJson(overriddenByLenient, objectType))
.isNull();
assertThat(overriddenByLenient.getStrictness()).isEqualTo(Strictness.STRICT);

JsonReader overriddenByLegacy = new JsonReader(new StringReader(input));
overriddenByLegacy.setStrictness(Strictness.STRICT);
assertWithMessage("case: %s", label)
.that(legacyStrictGson.fromJson(overriddenByLegacy, objectType))
.isNull();
assertThat(overriddenByLegacy.getStrictness()).isEqualTo(Strictness.STRICT);

assertWithMessage("case: %s", label).that(defaultGson.fromJson(input, Object.class)).isNull();
assertWithMessage("case: %s", label)
.that(legacyStrictGson.fromJson(input, Object.class))
.isNull();
assertWithMessage("case: %s", label).that(lenientGson.fromJson(input, Object.class)).isNull();
}
}

@Test
public void testFromJsonTruncatedDocumentStrictness() throws IOException {
Gson defaultGson = new Gson();
TypeToken<Object> objectType = TypeToken.get(Object.class);

// In STRICT mode, truncated mid-document input throws instead of returning null
JsonReader strictReader = new JsonReader(new StringReader("["));
strictReader.setStrictness(Strictness.STRICT);
strictReader.beginArray();
JsonSyntaxException e =
assertThrows(
JsonSyntaxException.class, () -> defaultGson.fromJson(strictReader, objectType));
assertThat(e).hasCauseThat().isInstanceOf(EOFException.class);
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.isEqualTo("End of input at line 1 column 2 path $[0]");

// In non-STRICT mode, legacy behavior still returns null
JsonReader lenientReader = new JsonReader(new StringReader("["));
lenientReader.setStrictness(Strictness.LENIENT);
lenientReader.beginArray();
assertThat(defaultGson.fromJson(lenientReader, objectType)).isNull();
}

@Test
public void testTreeTypeAdapterEmptyDocumentStrict() {
Gson deserializerGson =
new GsonBuilder()
.registerTypeAdapter(
CustomClass1.class,
(JsonDeserializer<CustomClass1>) (json, typeOfT, context) -> new CustomClass1())
.create();
TypeAdapter<CustomClass1> adapter = deserializerGson.getAdapter(CustomClass1.class);
JsonReader emptyStrictReader = new JsonReader(new StringReader(""));
emptyStrictReader.setStrictness(Strictness.STRICT);
JsonSyntaxException e =
assertThrows(JsonSyntaxException.class, () -> adapter.read(emptyStrictReader));
assertThat(e).hasCauseThat().isInstanceOf(EOFException.class);
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.isEqualTo("End of input at line 1 column 1 path $");

TypeAdapter<NonNullSafeDeserialized> nonNullSafeAdapter =
new Gson().getAdapter(NonNullSafeDeserialized.class);
JsonReader nonNullSafeStrictReader = new JsonReader(new StringReader(""));
nonNullSafeStrictReader.setStrictness(Strictness.STRICT);
JsonSyntaxException e2 =
assertThrows(
JsonSyntaxException.class, () -> nonNullSafeAdapter.read(nonNullSafeStrictReader));
assertThat(e2).hasCauseThat().isInstanceOf(EOFException.class);
assertThat(e2)
.hasCauseThat()
.hasMessageThat()
.isEqualTo("End of input at line 1 column 1 path $");
}

@JsonAdapter(value = NonNullSafeDeserializer.class, nullSafe = false)
private static class NonNullSafeDeserialized {}

private static class NonNullSafeDeserializer
implements JsonDeserializer<NonNullSafeDeserialized> {
@Override
public NonNullSafeDeserialized deserialize(
JsonElement json, Type typeOfT, JsonDeserializationContext context) {
return new NonNullSafeDeserialized();
}
}

private static class CustomClass1 {}

private static class CustomClass2 {}
Expand Down
Loading
Loading