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 package org.utgenome.gwt.utgb.client.util;
26
27 import java.util.ArrayList;
28 import java.util.Iterator;
29 import java.util.List;
30
31 import com.google.gwt.json.client.JSONArray;
32 import com.google.gwt.json.client.JSONParser;
33 import com.google.gwt.json.client.JSONString;
34 import com.google.gwt.json.client.JSONValue;
35
36 public class JSONUtil {
37
38
39
40
41 private JSONUtil() {
42 }
43
44
45
46
47
48
49
50 public static <T> String toJSONArray(List<T> iterable) {
51 JSONArray array = new JSONArray();
52 int index = 0;
53 for (Iterator<T> it = iterable.iterator(); it.hasNext();) {
54 array.set(index++, new JSONString(it.next().toString()));
55 }
56 return array.toString();
57 }
58
59 public static ArrayList<String> parseJSONArray(String jsonArray) {
60 if (jsonArray == null)
61 return new ArrayList<String>();
62
63 if (!jsonArray.startsWith("[") || !jsonArray.endsWith("]"))
64 throw new IllegalArgumentException("invalid json array data");
65
66 ArrayList<String> elementList = new ArrayList<String>();
67 JSONValue v = JSONParser.parse(jsonArray);
68 JSONArray array = v.isArray();
69 if (array != null) {
70 for (int i = 0; i < array.size(); i++)
71 elementList.add(toStringValue(array.get(i)));
72 }
73 return elementList;
74 }
75
76
77
78
79
80
81
82 public static String toStringValue(JSONValue value) {
83 if (value == null)
84 return "";
85
86 JSONString str = value.isString();
87 if (str != null)
88 return str.stringValue();
89 else
90 return value.toString();
91 }
92
93 }