Skip to content

Commit

Permalink
add extension function for addMixin on ObjectMapper and JsonMapper.Bu…
Browse files Browse the repository at this point in the history
…ilder
  • Loading branch information
Sylvain-maillard authored and Sylvain Maillard committed Apr 5, 2023
1 parent 82ad938 commit c908c25
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ inline fun <reified T> ObjectReader.readValueTyped(jp: JsonParser): T = readValu
inline fun <reified T> ObjectReader.readValuesTyped(jp: JsonParser): Iterator<T> = readValues(jp, jacksonTypeRef<T>())
inline fun <reified T> ObjectReader.treeToValue(n: TreeNode): T? = readValue(this.treeAsTokens(n), jacksonTypeRef<T>())

inline fun <reified T, reified U> ObjectMapper.addMixIn(): ObjectMapper = this.addMixIn(T::class.java, U::class.java)
inline fun <reified T, reified U> JsonMapper.Builder.addMixIn(): JsonMapper.Builder = this.addMixIn(T::class.java, U::class.java)

operator fun ArrayNode.plus(element: Boolean) = Unit.apply { add(element) }
operator fun ArrayNode.plus(element: Short) = Unit.apply { add(element) }
operator fun ArrayNode.plus(element: Int) = Unit.apply { add(element) }
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
package com.fasterxml.jackson.module.kotlin.test

import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.databind.json.JsonMapper
import com.fasterxml.jackson.databind.node.JsonNodeFactory
import com.fasterxml.jackson.module.kotlin.addMixIn
import com.fasterxml.jackson.module.kotlin.contains
import com.fasterxml.jackson.module.kotlin.convertValue
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.jsonMapper
import com.fasterxml.jackson.module.kotlin.minusAssign
import com.fasterxml.jackson.module.kotlin.plusAssign
import com.fasterxml.jackson.module.kotlin.readValue
Expand Down Expand Up @@ -82,4 +86,15 @@ class TestExtensionMethods {
val convertValueResult: List<Person> = mapper.convertValue(tree)
assertThat(convertValueResult, `is`(listOf(Person("Neo"))))
}
}

@Test fun mixInExtensionTest() {

data class Person(val name: String)
abstract class PersonMixIn { @JsonIgnore var name: String = "" }

val mapper: JsonMapper = jsonMapper { addMixIn<Person, PersonMixIn>() }
val serializedPerson: String = mapper.writeValueAsString(Person("test"))

assertThat(serializedPerson, `is`("{}"))
}
}

0 comments on commit c908c25

Please sign in to comment.