This repository has been archived by the owner on Mar 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathdefault-type-demo.groovy
74 lines (58 loc) · 2.4 KB
/
default-type-demo.groovy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
@Grab('com.fasterxml.jackson.core:jackson-databind:2.8.8')
import com.fasterxml.jackson.databind.ObjectMapper;
class Zoo {
Animal animal;
}
abstract class Animal {
String name;
protected Animal() { }
}
class Dog extends Animal {
double barkVolume;
Dog() { }
}
class Cat extends Animal {
boolean likesCream;
int lives;
Cat() { }
}
ObjectMapper mapper = new ObjectMapper();
Dog dog1 = new Dog();
dog1.name = 'dog1';
dog1.barkVolume = 1.2;
Cat cat1 = new Cat();
cat1.name = 'cat1';
cat1.likesCream = true;
cat1.lives = 10;
Zoo z0 = new Zoo();
z0.animal = dog1;
assert mapper.writeValueAsString(z0) == '{"animal":{"name":"dog1","barkVolume":1.2}}';
z0.animal = cat1;
assert mapper.writeValueAsString(z0) == '{"animal":{"name":"cat1","likesCream":true,"lives":10}}';
try {
Zoo zax = mapper.readValue('{"animal":{"name":"dog1","barkVolume":1.2}}', Zoo.class);
assert false;
} catch (com.fasterxml.jackson.databind.JsonMappingException e) {
assert e.message.startsWith('Can not construct instance of Animal: abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information');
}
try {
Zoo zax = mapper.readValue('{"animal":{"name":"cat1","likesCream":true,"lives":10}}', Zoo.class);
assert false;
} catch (com.fasterxml.jackson.databind.JsonMappingException e) {
assert e.message.startsWith('Can not construct instance of Animal: abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information');
}
mapper = new ObjectMapper(); // NEED new ObjectMapper instance to activate enableDefaultTyping()
mapper.enableDefaultTyping(); // equivalant to enableObjectTyping(DefaultTyping.OBJECT_AND_NON_CONCRETE);
z0.animal = dog1;
assert mapper.writeValueAsString(z0) == '{"animal":["Dog",{"name":"dog1","barkVolume":1.2}]}';
z0 = mapper.readValue('{"animal":["Dog",{"name":"dog1","barkVolume":1.2}]}', Zoo.class);
assert z0.animal.class == Dog.class;
assert z0.animal.name == 'dog1';
assert z0.animal.barkVolume == 1.2;
z0.animal = cat1;
assert mapper.writeValueAsString(z0) == '{"animal":["Cat",{"name":"cat1","likesCream":true,"lives":10}]}';
z0 = mapper.readValue('{"animal":["Cat",{"name":"cat1","likesCream":true,"lives":10}]}', Zoo.class);
assert z0.animal.class == Cat.class;
assert z0.animal.name == 'cat1';
assert z0.animal.likesCream == true;
assert z0.animal.lives == 10;