File tree Expand file tree Collapse file tree 2 files changed +53
-0
lines changed
src/test/kotlin/com/fasterxml/jackson/module/kotlin/test Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Original file line number Diff line number Diff line change @@ -141,6 +141,28 @@ These Kotlin classes are supported with the following fields for serialization/d
141
141
142
142
(others are likely to work, but may not be tuned for Jackson)
143
143
144
+ # Sealed classes without @JsonSubTypes
145
+ Subclasses can be detected automatically for sealed classes, since all possible subclasses are known
146
+ at compile-time to Kotlin. This makes ` com.fasterxml.jackson.annotation.JsonSubTypes ` redundant.
147
+ A ` com.fasterxml.jackson.annotation.@JsonTypeInfo ` annotation at the base-class is still necessary.
148
+
149
+ ``` kotlin
150
+ @JsonTypeInfo(use = JsonTypeInfo .Id .NAME )
151
+ sealed class SuperClass {
152
+ class A : SuperClass ()
153
+ class B : SuperClass ()
154
+ }
155
+
156
+ .. .
157
+ val mapper = jacksonObjectMapper()
158
+ val root: SuperClass = mapper.readValue(json)
159
+ when (root){
160
+ is A -> " It's A"
161
+ is B -> " It's B"
162
+ }
163
+ ```
164
+
165
+
144
166
# Configuration
145
167
146
168
The Kotlin module may be given a few configuration parameters at construction time;
Original file line number Diff line number Diff line change
1
+ package com.fasterxml.jackson.module.kotlin.test
2
+
3
+ import com.fasterxml.jackson.annotation.JsonTypeInfo
4
+ import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
5
+ import com.fasterxml.jackson.module.kotlin.test.SealedClassTest.SuperClass.B
6
+ import org.junit.Test
7
+ import kotlin.test.assertTrue
8
+
9
+ class SealedClassTest {
10
+ private val mapper = jacksonObjectMapper()
11
+
12
+ /* *
13
+ * Json of a Serialized B-Object.
14
+ */
15
+ private val jsonB = """ {"@type":"SealedClassTest${" $" } SuperClass${" $" } B"}"""
16
+
17
+ /* *
18
+ * Tests that the @JsonSubTypes-Annotation is not necessary when working with Sealed-Classes.
19
+ */
20
+ @Test
21
+ fun sealedClassWithoutSubTypes () {
22
+ val result = mapper.readValue(jsonB, SuperClass ::class .java)
23
+ assertTrue { result is B }
24
+ }
25
+
26
+ @JsonTypeInfo(use = JsonTypeInfo .Id .NAME )
27
+ sealed class SuperClass {
28
+ class A : SuperClass ()
29
+ class B : SuperClass ()
30
+ }
31
+ }
You can’t perform that action at this time.
0 commit comments