Skip to content

Commit 2aa3a30

Browse files
Handle EOF in skipElement correctly (#1475)
Improve EOF exception in consumeStringLenient Fixes #1474 Co-authored-by: Vsevolod Tolstopyatov <qwwdfsad@gmail.com>
1 parent fcb641a commit 2aa3a30

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

formats/json/commonMain/src/kotlinx/serialization/json/internal/JsonLexer.kt

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2017-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
2+
* Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
33
*/
44

55
package kotlinx.serialization.json.internal
@@ -366,6 +366,7 @@ internal class JsonLexer(private val source: String) {
366366
return takePeeked()
367367
}
368368
var current = skipWhitespaces()
369+
if (current >= source.length) fail("EOF", current)
369370
// Skip leading quotation mark
370371
val token = charToTokenClass(source[current])
371372
if (token == TC_STRING) {
@@ -445,16 +446,17 @@ internal class JsonLexer(private val source: String) {
445446
"found ] instead of }",
446447
source
447448
)
448-
tokenStack.removeAt(tokenStack.size - 1)
449+
tokenStack.removeLast()
449450
}
450451
TC_END_OBJ -> {
451452
if (tokenStack.last() != TC_BEGIN_OBJ) throw JsonDecodingException(
452453
currentPosition,
453454
"found } instead of ]",
454455
source
455456
)
456-
tokenStack.removeAt(tokenStack.size - 1)
457+
tokenStack.removeLast()
457458
}
459+
TC_EOF -> fail("Unexpected end of input due to malformed JSON during ignoring unknown keys")
458460
}
459461
consumeNextToken()
460462
if (tokenStack.size == 0) return

formats/json/commonTest/src/kotlinx/serialization/json/JsonModesTest.kt

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2017-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
2+
* Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
33
*/
44

55
package kotlinx.serialization.json
@@ -77,6 +77,20 @@ class JsonModesTest : JsonTestBase() {
7777
doTest("""{"a": 0, "strangeField": ["imma string with } bracket"]}""")
7878
}
7979

80+
@Serializable
81+
class Empty
82+
83+
@Test
84+
fun lenientThrowOnMalformedString() {
85+
fun doTest(input: String) {
86+
assertFailsWith<SerializationException> { lenient.decodeFromString(Empty.serializer(), input) }
87+
}
88+
doTest("""{"a":[{"b":[{"c":{}d",""e"":"}]}""")
89+
doTest("""{"a":[}""")
90+
doTest("""{"a":""")
91+
lenient.decodeFromString(Empty.serializer(), """{"a":[]}""") // should not throw
92+
}
93+
8094
@Test
8195
fun testSerializeQuotedJson() = parametrizedTest { useStreaming ->
8296
assertEquals(

0 commit comments

Comments
 (0)