Skip to content

Commit

Permalink
Fixed issue #130 Default Parameter Values when JSON value is null (#259)
Browse files Browse the repository at this point in the history
  • Loading branch information
NumezmaT authored and cowtowncoder committed Oct 26, 2019
1 parent 328918a commit 34f5f8d
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,15 @@ internal class KotlinValueInstantiator(
return@forEachIndexed
}

var paramVal = if (!isMissing || paramDef.isPrimitive() || jsonProp.hasInjectableValueId()) {
buffer.getParameter(jsonProp)
var paramVal:Any?
if (!isMissing || paramDef.isPrimitive() || jsonProp.hasInjectableValueId()) {
paramVal = buffer.getParameter(jsonProp)
if (paramVal == null && paramDef.isOptional) {
return@forEachIndexed
}
} else {
// trying to get suitable "missing" value provided by deserializer
jsonProp.valueDeserializer?.getNullValue(ctxt)
paramVal = jsonProp.valueDeserializer?.getNullValue(ctxt)
}

if (paramVal == null && ((nullToEmptyCollection && jsonProp.type.isCollectionLikeType) || (nullToEmptyMap && jsonProp.type.isMapLikeType))) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package com.fasterxml.jackson.module.kotlin.test

import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import org.junit.Assert
import org.junit.Test

class NullToDefault {

private fun createMapper() = jacksonObjectMapper()

private data class TestClass(val sku: Int = -1,
val text: String,
val name: String = "",
val images: String?,
val language: String = "uk",
val attribute: Int = 0,
val order: Int = -1)

@Test
fun shouldUseDefault() {
val item = createMapper().readValue<TestClass>("{\n" +
" \"sku\": \"974\",\n" +
" \"text\": \"plain\",\n" +
" \"name\": null,\n" +
" \"images\": null,\n" +
" \"attribute\": \"19\",\n" +
" \"new_item\": \"Composition: 100% polyester; 1.75 \"" +
" }")

Assert.assertTrue(item.sku == 974)
Assert.assertTrue(item.text == "plain")
Assert.assertTrue(item.name != null)
Assert.assertTrue(item.images == null)
Assert.assertTrue(item.language == "uk")
Assert.assertTrue(item.attribute == 19)
Assert.assertTrue(item.order == -1)
}

@Test
fun errorIfNotDefault() {
val item = createMapper().readValue<TestClass>("{\n" +
" \"sku\": \"974\",\n" +
" \"text\": null,\n" +
" \"attribute\": \"19\",\n" +
" \"name\": null,\n" +
" \"new_item\": \"Composition: 100% polyester; 1.75 \"" +
" }")

Assert.assertTrue(item.sku == 974)
Assert.assertTrue(item.language == "uk")
Assert.assertTrue(item.attribute == 19)
Assert.assertTrue(item.name != null)
Assert.assertTrue(item.order == -1)
}
}

0 comments on commit 34f5f8d

Please sign in to comment.