1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.opencastproject.util;
23
24 import static java.lang.String.format;
25 import static org.opencastproject.util.data.functions.Misc.cast;
26 import static org.opencastproject.util.data.functions.Misc.chuck;
27
28 import org.json.simple.parser.JSONParser;
29 import org.json.simple.parser.ParseException;
30
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Optional;
34 import java.util.Set;
35
36
37
38 public final class JsonObj {
39 private final Map json;
40
41
42 public JsonObj(Map json) {
43 this.json = json;
44 }
45
46
47 public static JsonObj jsonObj(Map json) {
48 return new JsonObj(json);
49 }
50
51
52 public static JsonObj jsonObj(String json) {
53 return new JsonObj(parse(json));
54 }
55
56 private static Map parse(String json) {
57 try {
58 return (Map) new JSONParser().parse(json);
59 } catch (ParseException e) {
60 return chuck(e);
61 }
62 }
63
64 public Set keySet() {
65 return json.keySet();
66 }
67
68 public JsonVal val(String key) {
69 return new JsonVal(get(Object.class, key));
70 }
71
72 public JsonObj obj(String key) {
73 return jsonObj(get(Map.class, key));
74 }
75
76 public JsonArr arr(String key) {
77 return new JsonArr(get(List.class, key));
78 }
79
80 public boolean has(String key) {
81 return json.containsKey(key);
82 }
83
84
85
86
87
88
89
90 public <A> A get(Class<A> ev, String key) {
91 final Object v = json.get(key);
92 if (v != null) {
93 try {
94 return cast(v, ev);
95 } catch (ClassCastException e) {
96 throw new RuntimeException(format("Key %s has not required type %s but %s", key, ev.getName(), v.getClass()
97 .getName()));
98 }
99 } else {
100 throw new RuntimeException(format("Key %s does not exist", key));
101 }
102 }
103
104
105
106
107
108
109
110 public <A> Optional<A> opt(Class<A> ev, String key) {
111 final Object v = json.get(key);
112 if (v != null) {
113 try {
114 return Optional.of(cast(v, ev));
115 } catch (ClassCastException e) {
116 return Optional.empty();
117 }
118 } else {
119 return Optional.empty();
120 }
121 }
122
123
124
125
126
127
128 public JsonObj getObj(String key) {
129 return jsonObj(get(Map.class, key));
130 }
131
132
133
134
135
136
137 public Optional<JsonObj> optObj(String key) {
138 return opt(Map.class, key).map(JsonObj::jsonObj);
139 }
140 }