From deaa3a6cd9f4676e0c826eadadd2f3d6dc857096 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 ef7b8751..2015b4ca 100644 --- a/gson/src/main/java/com/google/gson/Gson.java +++ b/gson/src/main/java/com/google/gson/Gson.java @@ -778,6 +778,15 @@ public final class Gson { /** * 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) { @@ -787,12 +796,19 @@ public final class Gson { 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 c6cc4d54..82c9740a 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 @@ package com.google.gson; 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 @@ public final class GsonTest extends TestCase { } @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("