1
+ package cn .colintree .aix .JsonUtils ;
2
+
3
+ import java .util .Iterator ;
4
+
5
+ import com .google .appinventor .components .runtime .ComponentContainer ;
6
+ import com .google .appinventor .components .runtime .util .YailList ;
7
+
8
+ import org .json .JSONArray ;
9
+ import org .json .JSONException ;
10
+ import org .json .JSONObject ;
11
+
12
+ /**
13
+ * A non visible container for JSONObject
14
+ */
15
+ public final class JsonObject extends JsonType {
16
+
17
+ public static JsonObject parseJsonObject (YailList list ) throws JSONException {
18
+ return new JsonObject (parseJSONObject (list ));
19
+ }
20
+
21
+ public static JSONObject parseJSONObject (YailList list ) throws JSONException {
22
+ if (!canParseJSONObject (list )) {
23
+ throw new IllegalArgumentException ();
24
+ }
25
+ int size = list .size ();
26
+ JSONObject object = new JSONObject ();
27
+ YailList itemList ;
28
+ for (int i = 0 ; i < size ; i ++) {
29
+ itemList = (YailList ) list .getObject (i );
30
+ object .put (
31
+ (String ) itemList .getObject (0 ),
32
+ itemList .getObject (1 ) instanceof YailList
33
+ ? JsonUtils .List2Json ((YailList ) itemList .getObject (1 ))
34
+ : itemList .getObject (1 )
35
+ );
36
+ }
37
+ return object ;
38
+ }
39
+
40
+ public static boolean canParseJSONObject (YailList list ) {
41
+ int size = list .size ();
42
+ Object item ;
43
+ for (int i = 0 ; i < size ; i ++) {
44
+ item = list .getObject (i );
45
+ if (item instanceof YailList && ((YailList )item ).size () == 2
46
+ && ((YailList )item ).getObject (0 ) instanceof String ) {
47
+ // this item is a valid object item
48
+ } else {
49
+ return false ;
50
+ }
51
+ }
52
+ return true ;
53
+ }
54
+
55
+
56
+ private final JSONObject object ;
57
+
58
+ JsonObject (ComponentContainer container ) {
59
+ this (new JSONObject ());
60
+ }
61
+ JsonObject (JSONObject object ) {
62
+ super (null );
63
+ this .object = object ;
64
+ }
65
+
66
+ @ Override
67
+ public String toString () {
68
+ return object .toString ();
69
+ }
70
+
71
+ public JSONObject getObject () {
72
+ return object ;
73
+ }
74
+
75
+ @ Override
76
+ public YailList toList () {
77
+ return toList (object );
78
+ }
79
+
80
+ public static YailList toList (JSONObject object ) {
81
+ int length = object .length ();
82
+ Object [] objs = new Object [length ];
83
+ int i = 0 ;
84
+ String key ;
85
+ Object value ;
86
+ Iterator <String > iterator = object .keys ();
87
+ while (iterator .hasNext ()) {
88
+ key = iterator .next ();
89
+ value = object .opt (key );
90
+ if (value instanceof JSONArray ) {
91
+ value = JsonArray .toList ((JSONArray ) value );
92
+ } else if (value instanceof JSONObject ) {
93
+ value = JsonObject .toList ((JSONObject ) value );
94
+ }
95
+ objs [i ] = YailList .makeList (new Object []{ key , value });
96
+ i ++;
97
+ }
98
+ return YailList .makeList (objs );
99
+ }
100
+
101
+ }
0 commit comments