Repository navigation
Expand file tree
/
Copy pathJSONHelperCore.java
More file actions
61 lines (50 loc) · 1.61 KB
/
Copy pathJSONHelperCore.java
File metadata and controls
61 lines (50 loc) · 1.61 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
package com.pubnub.api;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Iterator;
public class JSONHelperCore {
/**
* Get or create json path in original JSONObject.
*
* @param original object
* @param path to return
* @return JSONObject located at path.
*/
public static JSONObject getOrCreateObjectAtPath(JSONObject original, String path)
throws JSONException {
if (PubnubUtil.isBlank(path)) {
return original;
}
String[] pathElements = PubnubUtil.splitString(path, ".");
JSONObject 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);
}
return current;
}
/**
* Update leaf node
*
* @param original object
* @param value object
* @param location of value object
* @throws JSONException
*/
public static void updateJSONObjectValue(JSONObject original, Object value, String location)
throws JSONException {
int index = location.lastIndexOf(".");
JSONObject current = original;
String key = location;
if (index != -1) {
current = getOrCreateObjectAtPath(original, location.substring(0, index));
key = location.substring(index + 1);
}
current.put(key, value);
}
}