@@ -179,33 +179,36 @@ If you need to read and write values of Objects where there are multiple possibl
179
179
This can be done by adding ` @JsonTypeInfo ` annotation on ''base class'':
180
180
181
181
``` java
182
- // Include Java class name ("com.myempl.ImplClass") as JSON property "class "
183
- @JsonTypeInfo ( use = Id . CLASS , include = As . PROPERTY , property = " class" )
184
- public abstract class BaseClass {
182
+ @JsonTypeInfo ( use = Id . MINIMAL_CLASS , include = As . PROPERTY , property = " type " ) // Include Java class simple- name as JSON property "type "
183
+ @JsonSubTypes ({ @Type ( Car . class), @Type ( Aeroplane . class)}) // Required for deserialization only
184
+ public abstract class Vehicle {
185
185
}
186
-
187
- public class Impl1 extends BaseClass {
188
- public int x;
186
+ public class Car extends Vehicle {
187
+ public String licensePlate;
189
188
}
190
- public class Impl2 extends BaseClass {
191
- public String name ;
189
+ public class Aeroplane extends Vehicle {
190
+ public int wingSpan ;
192
191
}
193
192
194
193
public class PojoWithTypedObjects {
195
- public List<BaseClass > items;
194
+ public List<Vehicle > items;
196
195
}
197
196
```
198
197
199
- and this could result in serialized JSON like:
198
+ which gives serialized JSON like:
200
199
201
200
``` json
202
- { "items" : [
203
- { "class" : " Impl2 " , "name" : " Bob " },
204
- { "class" : " Impl1 " , "x" : 13 }
201
+ { "items" : [
202
+ { "type" : " Car " , "licensePlate" : " X12345 " },
203
+ { "type" : " Aeroplane " , "wingSpan" : 13 }
205
204
]}
206
205
```
207
206
208
- Note that this annotation has lots of configuration possibilities: for more information check out
207
+ Alternatively, ` @JsonTypeInfo(use=DEDUCTION) ` can be used to avoid requiring the 'type' field. For deserialization, types are _ deduced_ based
208
+ on the fields available. Exceptions will be raised if subtypes do not have a distinct signature of fieldnames or JSON does
209
+ not resolve to single known signature.
210
+
211
+ Note that ` @JsonTypeInfo ` has lots of configuration possibilities: for more information check out
209
212
[ Intro to polymorphic type handling] ( http://www.cowtowncoder.com/blog/archives/2010/03/entry_372.html )
210
213
211
214
### Changing property auto-detection
0 commit comments