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.Option.none;
26 import static org.opencastproject.util.data.Option.some;
27 import static org.opencastproject.util.data.functions.Misc.cast;
28 import static org.opencastproject.util.data.functions.Misc.chuck;
29
30 import org.opencastproject.util.data.Function;
31 import org.opencastproject.util.data.Option;
32
33 import org.json.simple.parser.JSONParser;
34 import org.json.simple.parser.ParseException;
35
36 import java.util.List;
37 import java.util.Map;
38 import java.util.Set;
39
40
41
42 public final class JsonObj {
43 private final Map json;
44
45
46 public JsonObj(Map json) {
47 this.json = json;
48 }
49
50
51 public static JsonObj jsonObj(Map json) {
52 return new JsonObj(json);
53 }
54
55
56 public static JsonObj jsonObj(String json) {
57 return new JsonObj(parse(json));
58 }
59
60
61 public static final Function<Map, JsonObj> jsonObj = new Function<Map, JsonObj>() {
62 @Override
63 public JsonObj apply(Map json) {
64 return jsonObj(json);
65 }
66 };
67
68 private static Map parse(String json) {
69 try {
70 return (Map) new JSONParser().parse(json);
71 } catch (ParseException e) {
72 return chuck(e);
73 }
74 }
75
76 public Set keySet() {
77 return json.keySet();
78 }
79
80 public JsonVal val(String key) {
81 return new JsonVal(get(Object.class, key));
82 }
83
84 public JsonObj obj(String key) {
85 return jsonObj(get(Map.class, key));
86 }
87
88 public JsonArr arr(String key) {
89 return new JsonArr(get(List.class, key));
90 }
91
92 public boolean has(String key) {
93 return json.containsKey(key);
94 }
95
96
97
98
99
100
101
102 public <A> A get(Class<A> ev, String key) {
103 final Object v = json.get(key);
104 if (v != null) {
105 try {
106 return cast(v, ev);
107 } catch (ClassCastException e) {
108 throw new RuntimeException(format("Key %s has not required type %s but %s", key, ev.getName(), v.getClass()
109 .getName()));
110 }
111 } else {
112 throw new RuntimeException(format("Key %s does not exist", key));
113 }
114 }
115
116
117
118
119
120
121
122 public <A> Option<A> opt(Class<A> ev, String key) {
123 final Object v = json.get(key);
124 if (v != null) {
125 try {
126 return some(cast(v, ev));
127 } catch (ClassCastException e) {
128 return none();
129 }
130 } else {
131 return none();
132 }
133 }
134
135
136
137
138
139
140 public JsonObj getObj(String key) {
141 return jsonObj(get(Map.class, key));
142 }
143
144
145
146
147
148
149 public Option<JsonObj> optObj(String key) {
150 return opt(Map.class, key).map(jsonObj);
151 }
152 }