blob: 50aaac0e2ff6cf719e7f249e4837cbc63135ff76 [file] [log] [blame]
Stuart McCullochbb014372012-06-07 21:57:32 +00001package aQute.lib.json;
2
3import java.lang.reflect.*;
4import java.util.*;
5
6public class ObjectHandler extends Handler {
7 @SuppressWarnings("rawtypes")
8 final Class rawClass;
9 final Field fields[];
10 final Type types[];
11 final Object defaults[];
12 final Field extra;
13
Stuart McCulloch2286f232012-06-15 13:27:53 +000014 ObjectHandler(JSONCodec codec, Class< ? > c) throws Exception {
Stuart McCullochbb014372012-06-07 21:57:32 +000015 rawClass = c;
16 fields = c.getFields();
17
18 // Sort the fields so the output is canonical
19 Arrays.sort(fields, new Comparator<Field>() {
20 public int compare(Field o1, Field o2) {
21 return o1.getName().compareTo(o2.getName());
22 }
23 });
24
25 types = new Type[fields.length];
26 defaults = new Object[fields.length];
27
28 Field x = null;
29 for (int i = 0; i < fields.length; i++) {
30 if (fields[i].getName().equals("__extra"))
31 x = fields[i];
32 types[i] = fields[i].getGenericType();
33 }
34 if (x != null && Map.class.isAssignableFrom(x.getType()))
35 extra = x;
36 else
37 extra = null;
Stuart McCulloch2286f232012-06-15 13:27:53 +000038
Stuart McCullochbb014372012-06-07 21:57:32 +000039 try {
40 Object template = c.newInstance();
41
42 for (int i = 0; i < fields.length; i++) {
43 defaults[i] = fields[i].get(template);
44 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000045 }
46 catch (Exception e) {
Stuart McCullochbb014372012-06-07 21:57:32 +000047 // Ignore
48 }
49 }
50
Stuart McCulloch2286f232012-06-15 13:27:53 +000051 @Override
52 void encode(Encoder app, Object object, Map<Object,Type> visited) throws Exception {
Stuart McCullochbb014372012-06-07 21:57:32 +000053 app.append("{");
54 String del = "";
55 for (int i = 0; i < fields.length; i++) {
56 if (fields[i].getName().startsWith("__"))
57 continue;
58
59 Object value = fields[i].get(object);
60 if (!app.writeDefaults) {
61 if (value == defaults[i])
62 continue;
63
64 if (value != null && value.equals(defaults[i]))
65 continue;
66 }
67
68 app.append(del);
69 StringHandler.string(app, fields[i].getName());
70 app.append(":");
71 app.encode(value, types[i], visited);
72 del = ",";
73 }
74 app.append("}");
75 }
76
Stuart McCulloch2286f232012-06-15 13:27:53 +000077 @SuppressWarnings("unchecked")
78 @Override
79 Object decodeObject(Decoder r) throws Exception {
Stuart McCullochbb014372012-06-07 21:57:32 +000080 assert r.current() == '{';
81 Object targetObject = rawClass.newInstance();
82
83 int c = r.next();
84 while (JSONCodec.START_CHARACTERS.indexOf(c) >= 0) {
85
86 // Get key
87 String key = r.codec.parseString(r);
88
89 // Get separator
90 c = r.skipWs();
91 if (c != ':')
92 throw new IllegalArgumentException("Expected ':' but got " + (char) c);
93
94 c = r.next();
95
96 // Get value
97
98 Field f = getField(key);
99 if (f != null) {
100 // We have a field and thus a type
101 Object value = r.codec.decode(f.getGenericType(), r);
Stuart McCulloch2286f232012-06-15 13:27:53 +0000102 if (value != null || !r.codec.ignorenull)
Stuart McCulloch285034f2012-06-12 12:41:16 +0000103 f.set(targetObject, value);
Stuart McCullochbb014372012-06-07 21:57:32 +0000104 } else {
105 // No field, but may extra is defined
106 if (extra == null) {
107 if (r.strict)
108 throw new IllegalArgumentException("No such field " + key);
109 Object value = r.codec.decode(null, r);
110 r.getExtra().put(rawClass.getName() + "." + key, value);
111 } else {
112
Stuart McCulloch2286f232012-06-15 13:27:53 +0000113 Map<String,Object> map = (Map<String,Object>) extra.get(targetObject);
Stuart McCullochbb014372012-06-07 21:57:32 +0000114 if (map == null) {
Stuart McCulloch2286f232012-06-15 13:27:53 +0000115 map = new LinkedHashMap<String,Object>();
Stuart McCullochbb014372012-06-07 21:57:32 +0000116 extra.set(targetObject, map);
117 }
118 Object value = r.codec.decode(null, r);
119 map.put(key, value);
120 }
121 }
122
123 c = r.skipWs();
124
125 if (c == '}')
126 break;
127
128 if (c == ',') {
129 c = r.next();
130 continue;
131 }
132
Stuart McCulloch2286f232012-06-15 13:27:53 +0000133 throw new IllegalArgumentException("Invalid character in parsing object, expected } or , but found "
134 + (char) c);
Stuart McCullochbb014372012-06-07 21:57:32 +0000135 }
136 assert r.current() == '}';
137 r.read(); // skip closing
138 return targetObject;
139 }
140
141 private Field getField(String key) {
142 for (int i = 0; i < fields.length; i++) {
143 int n = key.compareTo(fields[i].getName());
144 if (n == 0)
145 return fields[i];
146 if (n < 0)
147 return null;
148 }
149 return null;
150 }
151
152}