From 08bee302ecefbea5e58aa5a59886f8ccc24d04ea Mon Sep 17 00:00:00 2001 From: Marcono1234 Date: Mon, 1 Nov 2021 23:11:10 +0100 Subject: [PATCH] Fix `Gson.newJsonWriter` ignoring lenient and HTML-safe setting (#1989) * Improve Gson newJsonWriter and newJsonReader documentation * Consider lenient and HTML-safe setting for Gson.newJsonWriter * Remove empty line between imports --- gson/src/main/java/com/google/gson/Gson.java | 16 +++++ .../test/java/com/google/gson/GsonTest.java | 70 +++++++++++++++++++ 2 files changed, 86 insertions(+) diff --git a/gson/src/main/java/com/google/gson/Gson.java b/gson/src/main/java/com/google/gson/Gson.java index 299e2226ab..7b24648c4d 100644 --- a/gson/src/main/java/com/google/gson/Gson.java +++ b/gson/src/main/java/com/google/gson/Gson.java @@ -783,6 +783,15 @@ public void toJson(JsonElement jsonElement, Appendable writer) throws JsonIOExce /** * Returns a new JSON writer configured for the settings on this Gson instance. + * + *

The following settings are considered: + *

*/ public JsonWriter newJsonWriter(Writer writer) throws IOException { if (generateNonExecutableJson) { @@ -792,12 +801,19 @@ public JsonWriter newJsonWriter(Writer writer) throws IOException { if (prettyPrinting) { jsonWriter.setIndent(" "); } + jsonWriter.setHtmlSafe(htmlSafe); + jsonWriter.setLenient(lenient); jsonWriter.setSerializeNulls(serializeNulls); return jsonWriter; } /** * Returns a new JSON reader configured for the settings on this Gson instance. + * + *

The following settings are considered: + *

*/ public JsonReader newJsonReader(Reader reader) { JsonReader jsonReader = new JsonReader(reader); diff --git a/gson/src/test/java/com/google/gson/GsonTest.java b/gson/src/test/java/com/google/gson/GsonTest.java index c6cc4d5426..82c9740ab8 100644 --- a/gson/src/test/java/com/google/gson/GsonTest.java +++ b/gson/src/test/java/com/google/gson/GsonTest.java @@ -19,7 +19,10 @@ import com.google.gson.internal.Excluder; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; +import com.google.gson.stream.MalformedJsonException; import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.text.DateFormat; @@ -82,4 +85,71 @@ private static final class TestTypeAdapter extends TypeAdapter { } @Override public Object read(JsonReader in) throws IOException { return null; } } + + public void testNewJsonWriter_Default() throws IOException { + StringWriter writer = new StringWriter(); + JsonWriter jsonWriter = new Gson().newJsonWriter(writer); + jsonWriter.beginObject(); + jsonWriter.name("test"); + jsonWriter.nullValue(); + jsonWriter.name("