Stuart McCulloch | bb01437 | 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 | |
Stuart McCulloch | d482610 | 2012-06-26 16:34:24 +0000 | [diff] [blame] | 10 | ArrayHandler(@SuppressWarnings("unused") Class< ? > rawClass, Type componentType) { |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 11 | this.componentType = componentType; |
| 12 | } |
| 13 | |
| 14 | @Override |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 15 | void encode(Encoder app, Object object, Map<Object,Type> visited) throws IOException, Exception { |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 16 | app.append("["); |
| 17 | String del = ""; |
| 18 | int l = Array.getLength(object); |
| 19 | for (int i = 0; i < l; i++) { |
| 20 | app.append(del); |
| 21 | app.encode(Array.get(object, i), componentType, visited); |
| 22 | del = ","; |
| 23 | } |
| 24 | app.append("]"); |
| 25 | } |
| 26 | |
| 27 | @Override |
| 28 | Object decodeArray(Decoder r) throws Exception { |
| 29 | ArrayList<Object> list = new ArrayList<Object>(); |
| 30 | r.codec.parseArray(list, componentType, r); |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 31 | Object array = Array.newInstance(r.codec.getRawClass(componentType), list.size()); |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 32 | int n = 0; |
| 33 | for (Object o : list) |
| 34 | Array.set(array, n++, o); |
| 35 | |
| 36 | return array; |
| 37 | } |
| 38 | } |