forked from open-force/jsonparse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSONParse.cls
More file actions
258 lines (215 loc) · 8.35 KB
/
JSONParse.cls
File metadata and controls
258 lines (215 loc) · 8.35 KB
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
/*
MIT License
Copyright (c) 2018 open-force
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* Utility class to streamline parsing nested JSON data structures.
*
* @see https://github.com/open-force/jsonparse
*/
public with sharing class JSONParse {
private static final Pattern ARRAY_NOTATION = Pattern.compile('\\[(\\d+)\\]');
/**
* Every JSONParse instance is a wrapper around some actual data, which we store here.
*/
private Object value;
/**
* Create a JSONParse instance from a serialized JSON string.
*
* @param jsonData
*/
public JSONParse(String jsonData) {
value = JSON.deserializeUntyped(jsonData);
}
/**
* Create a JSONParse instance from data that has already been unmarshalled from a JSON string.
*
* @param value
*/
private JSONParse(Object value) {
this.value = value;
}
// ---------------------------------------
// ------ Interactions -------------------
// ---------------------------------------
/**
* Drill into a nested structure to get to some subtree in the document. We allow the path to include a mix
* of array notation and string keys.
*
* @param path
*
* @return A new JSONParse wrapper that wraps the targeted subtree.
* @throws NotAnArrayException if we try to apply an array notation to a node that isn't an array
* @throws NotAnObjectException if we try to apply a map key to a node that isn't an object
* @throws MissingKeyException if part of the path can't be resolved because there is no match on that key
*/
public JSONParse get(String path) {
JSONParse currentNode = this; // we start with ourselves and drill deeper
// drill down through the nested structure
for(String key : path.split('\\.')) {
// check to see if we are going to parse this key as a reference to an array item
Matcher arrayMatcher = ARRAY_NOTATION.matcher(key);
if(arrayMatcher.matches()) {
Integer index = Integer.valueOf(arrayMatcher.group(1));
currentNode = currentNode.asList().get(index);
}
else { // otherwise, treat this key as a normal map key
Map<String, JSONParse> wrappedMap = currentNode.asMap();
if(!wrappedMap.containsKey(key)) {
throw new MissingKeyException('No match found for <' + key + '>: ' + wrappedMap.keySet());
}
currentNode = wrappedMap.get(key);
}
}
return currentNode;
}
/**
* Make an assumption that this JSONParse instance wraps a JSON object, and attempt to return a Map of the values.
*
* @return A Map of JSONParse instances
* @throws NotAnObjectException if the internal wrapped value is not a JSON object
*/
public Map<String, JSONParse> asMap() {
if(!isObject()) {
throw new NotAnObjectException('The wrapped value is not a JSON object:\n' + toStringPretty());
}
Map<String, Object> valueAsMap = (Map<String, Object>)value;
Map<String, JSONParse> wrappers = new Map<String, JSONParse>();
for(String key : valueAsMap.keySet()) {
wrappers.put(key, new JSONParse(valueAsMap.get(key)));
}
return wrappers;
}
/**
* Make an assumption that this JSONParse instance wraps a List, and attempt to return an iterable version
* of the values.
*
* @return A List of JSONParse instances, each wrapping one of the List items
* @throws NotAnArrayException if the internal wrapped value is not a List instance
*/
public List<JSONParse> asList() {
if(!isArray()) {
throw new NotAnArrayException('The wrapped value is not a JSON array:\n' + toStringPretty());
}
List<JSONParse> wrappers = new List<JSONParse>();
for(Object item : (List<Object>)value) {
wrappers.add(new JSONParse(item));
}
return wrappers;
}
// ---------------------------------------
// ------ Utility ------------------------
// ---------------------------------------
public Boolean isObject() {
return value instanceof Map<String, Object>;
}
public Boolean isArray() {
return value instanceof List<Object>;
}
public String toStringPretty() {
return JSON.serializePretty(value);
}
// ---------------------------------------
// ------ Value Extraction ---------------
// ---------------------------------------
public Blob getBlobValue() {
if(value instanceof String)
return EncodingUtil.base64Decode((String)value);
throw new InvalidConversionException('Only String values can be converted to a Blob: ' + toStringPretty());
}
public Boolean getBooleanValue() {
if(value instanceof Boolean)
return (Boolean)value;
return Boolean.valueOf(value);
}
public Datetime getDatetimeValue() {
if(value instanceof Long)
return Datetime.newInstance((Long)value);
if(value instanceof String)
return Datetime.valueOfGmt(((String)value).replace('T', ' '));
throw new InvalidConversionException('Only Long and String values can be converted to a Datetime: ' + toStringPretty());
}
public Date getDateValue() {
if(value instanceof Long)
return Datetime.newInstance((Long)value).dateGmt();
if(value instanceof String)
return Date.valueOf((String)value);
throw new InvalidConversionException('Only Long and String values can be converted to a Date: ' + toStringPretty());
}
public Decimal getDecimalValue() {
if(value instanceof Decimal)
return (Decimal)value;
if(value instanceof String)
return Decimal.valueOf((String)value);
throw new InvalidConversionException('This value cannot be converted to a Decimal: ' + toStringPretty());
}
public Double getDoubleValue() {
if(value instanceof Double)
return (Double)value;
if(value instanceof String)
return Double.valueOf((String)value);
throw new InvalidConversionException('This value cannot be converted to a Double: ' + toStringPretty());
}
public Id getIdValue() {
if(value instanceof String)
return Id.valueOf((String)value);
throw new InvalidConversionException('This value cannot be converted to an Id: ' + toStringPretty());
}
public Integer getIntegerValue() {
if(value instanceof Integer)
return (Integer)value;
if(value instanceof Decimal)
return ((Decimal)value).intValue();
if(value instanceof String)
return Integer.valueOf((String)value);
throw new InvalidConversionException('This value cannot be converted to an Integer: ' + toStringPretty());
}
public Long getLongValue() {
if(value instanceof Long)
return (Long)value;
if(value instanceof Decimal)
return ((Decimal)value).longValue();
if(value instanceof String)
return Long.valueOf((String)value);
throw new InvalidConversionException('This value cannot be converted to a Long: ' + toStringPretty());
}
public String getStringValue() {
if(isObject() || isArray())
throw new InvalidConversionException('Objects and arrays are not Strings: ' + toStringPretty());
if(value instanceof String)
return (String)value;
return String.valueOf(value);
}
public Time getTimeValue() {
if(value instanceof Long)
return Datetime.newInstance((Long)value).timeGmt();
if(value instanceof String)
return Datetime.valueOfGmt(((String)value).replace('T', ' ')).timeGmt();
throw new InvalidConversionException('Only Long and String values can be converted to a Time: ' + toStringPretty());
}
public Object getValue() {
return value;
}
// ---------------------------------------
// ------ Exceptions ---------------------
// ---------------------------------------
public class NotAnObjectException extends Exception {}
public class NotAnArrayException extends Exception {}
public class MissingKeyException extends Exception {}
public class InvalidConversionException extends Exception {}
}