File tree 2 files changed +57
-0
lines changed
src/test/kotlin/com/fasterxml/jackson/module/kotlin/test
2 files changed +57
-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.A
6
+ import com.fasterxml.jackson.module.kotlin.test.SealedClassTest.SuperClass.B
7
+ import org.junit.Test
8
+ import kotlin.test.assertTrue
9
+
10
+ class SealedClassTest {
11
+
12
+
13
+ private val mapper = jacksonObjectMapper()
14
+
15
+ /* *
16
+ * Json of a Serialized B-Object.
17
+ */
18
+ private val jsonB = " {\" @type\" :\" SealedClassTest\$ SuperClass\$ B\" }"
19
+
20
+ /* *
21
+ * Tests that the @JsonSubTypes-Annotation is not necessary when working with Sealed-Classes.
22
+ *
23
+ */
24
+ @Test fun SealedClassWithoutSubTypes (){
25
+ val result = mapper.readValue(jsonB, SuperClass ::class .java)
26
+ assertTrue { result is B }
27
+ }
28
+
29
+ @JsonTypeInfo(use = JsonTypeInfo .Id .NAME )
30
+ sealed class SuperClass {
31
+ class A :SuperClass ()
32
+ class B :SuperClass ()
33
+ }
34
+
35
+ }
You can’t perform that action at this time.
0 commit comments