Skip to content

Commit e0c5ec2

Browse files
committed
Added Test and Documentation for the sealed-classes-without-@JsonSubTypes_Feature.
(cherry picked from commit 59ea94c)
1 parent acf8651 commit e0c5ec2

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

README.md

+22
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,28 @@ These Kotlin classes are supported with the following fields for serialization/d
141141

142142
(others are likely to work, but may not be tuned for Jackson)
143143

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+
144166
# Configuration
145167

146168
The Kotlin module may be given a few configuration parameters at construction time;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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+
}

0 commit comments

Comments
 (0)