From 78091aeb461a0c34acd264eb553554a297e63d33 Mon Sep 17 00:00:00 2001 From: Eric Cochran Date: Sun, 15 Apr 2018 06:39:04 -0700 Subject: [PATCH] Fix JsonUtf8Writer to be strict about names in the wrong place. (#502) --- .../com/squareup/moshi/JsonUtf8Writer.java | 3 +- .../com/squareup/moshi/JsonWriterTest.java | 33 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/moshi/src/main/java/com/squareup/moshi/JsonUtf8Writer.java b/moshi/src/main/java/com/squareup/moshi/JsonUtf8Writer.java index 221f259..4fa074d 100644 --- a/moshi/src/main/java/com/squareup/moshi/JsonUtf8Writer.java +++ b/moshi/src/main/java/com/squareup/moshi/JsonUtf8Writer.java @@ -138,7 +138,8 @@ final class JsonUtf8Writer extends JsonWriter { if (stackSize == 0) { throw new IllegalStateException("JsonWriter is closed."); } - if (deferredName != null) { + int context = peekScope(); + if ((context != EMPTY_OBJECT && context != NONEMPTY_OBJECT) || deferredName != null) { throw new IllegalStateException("Nesting problem."); } deferredName = name; diff --git a/moshi/src/test/java/com/squareup/moshi/JsonWriterTest.java b/moshi/src/test/java/com/squareup/moshi/JsonWriterTest.java index 1a18715..0fa61fd 100644 --- a/moshi/src/test/java/com/squareup/moshi/JsonWriterTest.java +++ b/moshi/src/test/java/com/squareup/moshi/JsonWriterTest.java @@ -571,4 +571,37 @@ public final class JsonWriterTest { writer.close(); writer.close(); } + + @Test public void nameNotInObjectFails() throws IOException { + JsonWriter writer = factory.newWriter(); + try { + writer.name("a"); + fail(); + } catch (IllegalStateException expected) { + assertThat(expected).hasMessage("Nesting problem."); + } + } + + @Test public void missingValueInObjectIsANestingProblem() throws IOException { + JsonWriter writer = factory.newWriter(); + writer.beginObject(); + writer.name("a"); + try { + writer.name("b"); + fail(); + } catch (IllegalStateException expected) { + assertThat(expected).hasMessage("Nesting problem."); + } + } + + @Test public void nameInArrayIsANestingProblem() throws IOException { + JsonWriter writer = factory.newWriter(); + writer.beginArray(); + try { + writer.name("a"); + fail(); + } catch (IllegalStateException expected) { + assertThat(expected).hasMessage("Nesting problem."); + } + } }