Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 1 | package aQute.lib.json; |
| 2 | |
| 3 | import java.lang.reflect.*; |
| 4 | import java.math.*; |
| 5 | import java.util.*; |
| 6 | |
| 7 | public class NumberHandler extends Handler { |
| 8 | final Class<?> type; |
| 9 | |
| 10 | NumberHandler(Class<?> clazz) { |
| 11 | this.type = clazz; |
| 12 | } |
| 13 | |
| 14 | @Override void encode(Encoder app, Object object, Map<Object, Type> visited) |
| 15 | throws Exception { |
| 16 | String s = object.toString(); |
| 17 | if ( s.endsWith(".0")) |
| 18 | s = s.substring(0,s.length()-2); |
| 19 | |
| 20 | app.append(s); |
| 21 | } |
| 22 | |
| 23 | @Override Object decode(boolean s) { |
| 24 | return decode(s ? 1d : 0d); |
| 25 | } |
| 26 | |
| 27 | @Override Object decode(String s) { |
| 28 | double d = Double.parseDouble(s); |
| 29 | return decode(d); |
| 30 | } |
| 31 | |
| 32 | @Override Object decode() { |
| 33 | return decode(0d); |
| 34 | } |
| 35 | |
| 36 | @Override Object decode(Number s) { |
| 37 | double dd = s.doubleValue(); |
| 38 | |
| 39 | if (type == double.class || type == Double.class) |
| 40 | return s.doubleValue(); |
| 41 | |
| 42 | if ((type == int.class || type == Integer.class) |
| 43 | && within(dd, Integer.MIN_VALUE, Integer.MAX_VALUE)) |
| 44 | return s.intValue(); |
| 45 | |
| 46 | if ((type == long.class || type == Long.class) && within(dd, Long.MIN_VALUE, Long.MAX_VALUE)) |
| 47 | return s.longValue(); |
| 48 | |
| 49 | if ((type == byte.class || type == Byte.class) && within(dd, Byte.MIN_VALUE, Byte.MAX_VALUE)) |
| 50 | return s.byteValue(); |
| 51 | |
| 52 | if ((type == short.class || type == Short.class) |
| 53 | && within(dd, Short.MIN_VALUE, Short.MAX_VALUE)) |
| 54 | return s.shortValue(); |
| 55 | |
| 56 | if (type == float.class || type == Float.class) |
| 57 | return s.floatValue(); |
| 58 | |
| 59 | if (type == BigDecimal.class) |
| 60 | return BigDecimal.valueOf(dd); |
| 61 | |
| 62 | if (type == BigInteger.class) |
| 63 | return BigInteger.valueOf(s.longValue()); |
| 64 | |
| 65 | throw new IllegalArgumentException("Unknown number format: " + type); |
| 66 | } |
| 67 | |
| 68 | private boolean within(double s, double minValue, double maxValue) { |
| 69 | return s >= minValue && s <= maxValue; |
| 70 | } |
| 71 | } |