forked from ringcentral/pubnub-jtools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSONHelper.java
More file actions
75 lines (60 loc) · 2.14 KB
/
JSONHelper.java
File metadata and controls
75 lines (60 loc) · 2.14 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
package com.pubnub.api;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Iterator;
public class JSONHelper extends JSONHelperCore {
/**
* Merge original and newObject. Does not support JSONArrays.
*
* @param original object
* @param newObject object
* @throws JSONException
*/
public static JSONObject merge(JSONObject original, JSONObject newObject) throws JSONException {
return merge(original, newObject, null);
}
/**
* Merge original and newObject at specified location. Does not support JSONArrays.
*
* @param original object
* @param newObject object
* @param location path
* @throws JSONException
*/
public static JSONObject merge(JSONObject original, JSONObject newObject, String location) throws JSONException {
JSONObject current;
if (PubnubUtil.isBlank(location)) {
current = original;
} else {
String[] pathElements = PubnubUtil.splitString(location, ".");
current = original;
int length = pathElements.length;
//noinspection ForLoopReplaceableByForEach
for (int i = 0; i < length; i++) {
String key = pathElements[i];
if (!current.has(key)) {
current.put(key, new JSONObject());
}
current = current.getJSONObject(key);
}
}
Iterator fieldNames = newObject.keys();
Object newNode;
Object originalNode;
while (fieldNames.hasNext()) {
String fieldName = (String) fieldNames.next();
newNode = newObject.get(fieldName);
try {
originalNode = current.get(fieldName);
} catch (JSONException e) {
originalNode = null;
}
if (originalNode instanceof JSONObject && newNode instanceof JSONObject) {
current.put(fieldName, merge((JSONObject) originalNode, (JSONObject) newNode));
} else {
current.put(fieldName, newNode);
}
}
return original;
}
}