Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle EOF in skipElement correctly #1475

Merged
merged 2 commits into from
May 12, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2017-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
* Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/

package kotlinx.serialization.json.internal
Expand Down Expand Up @@ -366,6 +366,7 @@ internal class JsonLexer(private val source: String) {
return takePeeked()
}
var current = skipWhitespaces()
if (current >= source.length) fail("EOF", current)
// Skip leading quotation mark
val token = charToTokenClass(source[current])
if (token == TC_STRING) {
Expand Down Expand Up @@ -445,16 +446,17 @@ internal class JsonLexer(private val source: String) {
"found ] instead of }",
source
)
tokenStack.removeAt(tokenStack.size - 1)
tokenStack.removeLast()
}
TC_END_OBJ -> {
if (tokenStack.last() != TC_BEGIN_OBJ) throw JsonDecodingException(
currentPosition,
"found } instead of ]",
source
)
tokenStack.removeAt(tokenStack.size - 1)
tokenStack.removeLast()
}
TC_EOF -> fail("Unexpected end of input, possibly due to malformed JSON")
sandwwraith marked this conversation as resolved.
Show resolved Hide resolved
}
consumeNextToken()
if (tokenStack.size == 0) return
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2017-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
* Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/

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

@Serializable
class Empty

@Test
fun lenientThrowOnMalformedString() {
fun doTest(input: String) {
assertFailsWith<SerializationException> { lenient.decodeFromString(Empty.serializer(), input) }
}
doTest("""{"a":[{"b":[{"c":{}d",""e"":"}]}""")
doTest("""{"a":[}""")
doTest("""{"a":""")
lenient.decodeFromString(Empty.serializer(), """{"a":[]}""") // should not throw
}

@Test
fun testSerializeQuotedJson() = parametrizedTest { useStreaming ->
assertEquals(
Expand Down