Stuart McCulloch | f317322 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 1 | package aQute.lib.json; |
| 2 | |
| 3 | import java.io.*; |
| 4 | import java.lang.reflect.*; |
| 5 | import java.util.*; |
| 6 | |
| 7 | public class ArrayHandler extends Handler { |
| 8 | Type componentType; |
| 9 | |
| 10 | ArrayHandler(Class< ? > rawClass, Type componentType) { |
| 11 | this.componentType = componentType; |
| 12 | } |
| 13 | |
| 14 | @Override |
| 15 | void encode(Encoder app, Object object, Map<Object, Type> visited) |
| 16 | throws IOException, Exception { |
| 17 | app.append("["); |
| 18 | String del = ""; |
| 19 | int l = Array.getLength(object); |
| 20 | for (int i = 0; i < l; i++) { |
| 21 | app.append(del); |
| 22 | app.encode(Array.get(object, i), componentType, visited); |
| 23 | del = ","; |
| 24 | } |
| 25 | app.append("]"); |
| 26 | } |
| 27 | |
| 28 | @Override |
| 29 | Object decodeArray(Decoder r) throws Exception { |
| 30 | ArrayList<Object> list = new ArrayList<Object>(); |
| 31 | r.codec.parseArray(list, componentType, r); |
| 32 | Object array = Array.newInstance(r.codec.getRawClass(componentType), |
| 33 | list.size()); |
| 34 | int n = 0; |
| 35 | for (Object o : list) |
| 36 | Array.set(array, n++, o); |
| 37 | |
| 38 | return array; |
| 39 | } |
| 40 | } |