Skip to content

Commit

Permalink
Don't throw NoSuchElement if key is missing in the map in `Mapper.rea…
Browse files Browse the repository at this point in the history
…dNotNullMark`,

because tag can be only prefix for nested object

Fixes #182
  • Loading branch information
sandwwraith committed Aug 6, 2018
1 parent 0c4ed9e commit 2151df1
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,12 @@ object Mapper {
class InNullableMapper(val map: Map<String, Any?>) : NamedValueInput() {
override fun readTaggedValue(tag: String): Any = map.getValue(tag)!!

override fun readTaggedNotNullMark(tag: String): Boolean = map.getValue(tag) != null
override fun readTaggedNotNullMark(tag: String): Boolean {
return tag !in map || // in case of complex object, its fields are
// prefixed with dot and there are no 'clean' tag with object name.
// Invalid tags can be handled later, in .readValue
map.getValue(tag) != null
}
}

inline fun <reified T : Any> map(obj: T): Map<String, Any> {
Expand All @@ -384,4 +389,4 @@ object Mapper {
val m = InNullableMapper(map)
return m.read()
}
}
}
32 changes: 30 additions & 2 deletions runtime/common/src/test/kotlin/kotlinx/serialization/MapperTest.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package kotlinx.serialization

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.*

class MapperTest {

Expand All @@ -14,6 +13,13 @@ class MapperTest {
@Serializable
data class NullableData(val nullable: String?, val nullable2: String?, val property: String)

@Serializable
data class Category(var name: String? = null,
var subCategory: SubCategory? = null)

@Serializable
data class SubCategory(var name: String? = null)

@Test
fun testListTagStack() {
val data = Data(listOf("element1"), "property")
Expand Down Expand Up @@ -48,4 +54,26 @@ class MapperTest {
assertEquals(data.nullable2, unmap.nullable2)
assertEquals(data.property, unmap.property)
}

@Test
fun testNestedNull() {
val category = Category(name = "Name")
val map = Mapper.mapNullable(category)
val recreatedCategory = Mapper.unmapNullable<Category>(map)
assertEquals(category, recreatedCategory)
}

@Test
fun testNestedNullable() {
val category = Category(name = "Name", subCategory = SubCategory())
val map = Mapper.mapNullable(category)
val recreatedCategory = Mapper.unmapNullable<Category>(map)
assertEquals(category, recreatedCategory)
}

@Test
fun failsOnIncorrectMaps() {
val map: Map<String, Any?> = mapOf("name" to "Name")
assertFailsWith<NoSuchElementException> { Mapper.unmapNullable<Category>(map) }
}
}

0 comments on commit 2151df1

Please sign in to comment.