-
Notifications
You must be signed in to change notification settings - Fork 116
/
Copy pathCustomJsonSubObjectsTest.java
223 lines (205 loc) · 7.13 KB
/
CustomJsonSubObjectsTest.java
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
package com.cedarsoftware.io;
import java.io.IOException;
import java.io.Writer;
import java.time.OffsetDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import com.cedarsoftware.util.CompactMap;
import com.cedarsoftware.util.DeepEquals;
import com.cedarsoftware.util.convert.Converter;
import org.junit.jupiter.api.Test;
/**
* @author John DeRegnaucourt ([email protected])
* <br>
* Copyright (c) Cedar Software LLC
* <br><br>
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <br><br>
* <a href="http://www.apache.org/licenses/LICENSE-2.0">License</a>
* <br><br>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class CustomJsonSubObjectsTest
{
static class Person {
private String firstName;
private String lastName;
private String phoneNumber;
private OffsetDateTime dob;
private TestObjectKid[] kids;
private Object[] friends;
private List<TestObjectKid> pets;
private Map<String, Object> items;
}
/**
* Custom Reader for the Person object's local fields.
*/
static class PersonFactory implements JsonReader.ClassFactory {
@SuppressWarnings("unchecked")
public Object newInstance(Class<?> c, JsonObject jsonObj, Resolver resolver) {
Person person = new Person(); // Factory - create Java peer instance - root class only.
Map<String, Object> map = (Map) jsonObj;
Converter converter = resolver.getConverter();
// Scoop values from JsonObject
person.firstName = converter.convert(map.get("first"), String.class);
person.lastName = converter.convert(map.get("last"), String.class);
person.phoneNumber = converter.convert(map.get("phone"), String.class);
person.dob = converter.convert(map.get("dob"), OffsetDateTime.class);
// Handle the complex field types by delegating to the Resolver, which will place these on its internal
// work stack, and ultimately map the values from the JsonObject (Map) to the peer Java instance.
person.kids = (TestObjectKid[]) resolver.createJavaFromJson(map.get("kids"));
person.friends = (Object[]) resolver.createJavaFromJson(map.get("friends"));
person.pets = (List<TestObjectKid>) resolver.createJavaFromJson(map.get("pets"));
person.items = (Map<String, Object>) resolver.createJavaFromJson(map.get("items"));
return person;
}
}
static class PersonWriter implements JsonWriter.JsonClassWriter {
public void write(Object o, boolean showType, Writer output, WriterContext context) throws IOException {
Person p = (Person) o;
// Changing the field names on the Person class
output.write("\"first\":\"");
output.write(p.firstName);
output.write("\",\"last\":\"");
output.write(p.lastName);
output.write("\",\"phone\":\"");
output.write(p.phoneNumber);
output.write("\",\"dob\":\"");
output.write(p.dob.toString());
// Handles substructure, with unknown depth here.
output.write("\",\"kids\":");
context.writeImpl(p.kids, true);
output.write(",\"friends\":");
context.writeImpl(p.friends, false);
output.write(",\"pets\":");
context.writeImpl(p.pets, true);
output.write(",\"items\":");
context.writeImpl(p.items, true);
}
}
Person createPersonJohn() {
Person john = new Person();
john.firstName = "John";
john.lastName = "Smith";
john.phoneNumber = "213-555-1212";
john.dob = OffsetDateTime.parse("1976-07-04T16:20:00-08:00");
john.kids = new TestObjectKid[] {new TestObjectKid("Lisa", "[email protected]"), new TestObjectKid("Annie", "[email protected]")};
// Put a cycle in the object graph
john.kids[0]._other = john.kids[1];
john.kids[1]._other = john.kids[0];
john.friends = new Object[] { new TestObjectKid("Ken", "[email protected]"), new TestObjectKid("Josh", "[email protected]") };
john.pets = Arrays.asList(new TestObjectKid("Eddie", "[email protected]"), new TestObjectKid("Bella", "[email protected]"));
john.items = new CompactMap<>();
john.items.put("laptop", "Apple Macbook Pro M3");
john.items.put("phone", "Samsung Galaxy S20");
john.items.put("bitcoin", 8.5);
return john;
}
@Test
void testCustomReaderSimpleJavaMode()
{
// You do not need to create all the aliases, I did that to make the JSON look cleaner.
ReadOptionsBuilder readOptions = new ReadOptionsBuilder()
.addClassFactory(Person.class, new PersonFactory())
.aliasTypeName(Person.class, "Person")
.aliasTypeName(TestObjectKid.class, "TestObjKid")
.aliasTypeName(TestObjectKid[].class, "TestObjKid[]")
.aliasTypeName(CompactMap.class, "CompactMap");
WriteOptionsBuilder writeOptions = new WriteOptionsBuilder()
.addCustomWrittenClass(Person.class, new PersonWriter())
.aliasTypeName(Person.class, "Person")
.aliasTypeName(TestObjectKid.class, "TestObjKid")
.aliasTypeName(TestObjectKid[].class, "TestObjKid[]")
.aliasTypeName(CompactMap.class, "CompactMap");
// Note: You could use the ReadOptionsBuilder/WriteOptionsBuilder's static "addPermanent()" APIs instead of
// calling the ReadOptions/WriteOptions each time for transfer (for some options). This will set them for
// JVM lifecycle scope.
//
// Examples:
//
// WriteOptionsBuilder.addPermanentWriter(Person.class, new PersonWriter());
// ReadOptionsBuilder.addPermanentReader(Person.class, new PersonReader());
//
// WriteOptionsBuilder.addPermanentAlias(CompactMap.class, "CompactMap");
// ReadOptionsBuilder.addPermanentAlias(CompactMap.class, "CompactMap");
Person p1 = createPersonJohn();
String json = JsonIo.toJson(p1, writeOptions.build());
Person p2 = JsonIo.toObjects(json, readOptions.build(), Person.class);
assert DeepEquals.deepEquals(p1, p2);
}
/* Here's the JSON that was Written/Read
{
"@type": "Person",
"first": "John",
"last": "Smith",
"phone": "213-555-1212",
"dob": "1976-07-04T16:20-08:00",
"kids": {
"@type": "TestObjKid[]",
"@items": [
{
"@id": 2,
"_email": "[email protected]",
"_name": "Lisa",
"_other": {
"@id": 1,
"@type": "TestObjKid",
"_email": "[email protected]",
"_name": "Annie",
"_other": {
"@ref": 2
}
}
},
{
"@ref": 1
}
]
},
"friends": [
{
"@type": "TestObjKid",
"_email": "[email protected]",
"_name": "Ken",
"_other": null
},
{
"@type": "TestObjKid",
"_email": "[email protected]",
"_name": "Josh",
"_other": null
}
],
"pets": {
"@type": "ArraysAsList",
"@items": [
{
"@type": "TestObjKid",
"_email": "[email protected]",
"_name": "Eddie",
"_other": null
},
{
"@type": "TestObjKid",
"_email": "[email protected]",
"_name": "Bella",
"_other": null
}
]
},
"items": {
"@type": "CompactMap",
"laptop": "Apple Macbook Pro M3",
"phone": "Samsung Galaxy S20",
"bitcoin": 8.5
}
}
*/
}