blob: 310ca3e06d1a7a634992f928af655ae86a252541 [file] [log] [blame]
Stuart McCullochbb014372012-06-07 21:57:32 +00001package aQute.lib.json;
2
3import java.lang.reflect.*;
4import java.math.*;
5import java.util.*;
6
7public class NumberHandler extends Handler {
Stuart McCulloch2286f232012-06-15 13:27:53 +00008 final Class< ? > type;
Stuart McCullochbb014372012-06-07 21:57:32 +00009
Stuart McCulloch2286f232012-06-15 13:27:53 +000010 NumberHandler(Class< ? > clazz) {
Stuart McCullochbb014372012-06-07 21:57:32 +000011 this.type = clazz;
12 }
13
Stuart McCulloch2286f232012-06-15 13:27:53 +000014 @Override
15 void encode(Encoder app, Object object, Map<Object,Type> visited) throws Exception {
Stuart McCullochbb014372012-06-07 21:57:32 +000016 String s = object.toString();
Stuart McCulloch2286f232012-06-15 13:27:53 +000017 if (s.endsWith(".0"))
18 s = s.substring(0, s.length() - 2);
19
Stuart McCullochbb014372012-06-07 21:57:32 +000020 app.append(s);
21 }
22
Stuart McCulloch2286f232012-06-15 13:27:53 +000023 @Override
24 Object decode(boolean s) {
Stuart McCullochbb014372012-06-07 21:57:32 +000025 return decode(s ? 1d : 0d);
26 }
27
Stuart McCulloch2286f232012-06-15 13:27:53 +000028 @Override
29 Object decode(String s) {
Stuart McCullochbb014372012-06-07 21:57:32 +000030 double d = Double.parseDouble(s);
31 return decode(d);
32 }
33
Stuart McCulloch2286f232012-06-15 13:27:53 +000034 @Override
35 Object decode() {
Stuart McCullochbb014372012-06-07 21:57:32 +000036 return decode(0d);
37 }
38
Stuart McCulloch2286f232012-06-15 13:27:53 +000039 @Override
40 Object decode(Number s) {
Stuart McCullochbb014372012-06-07 21:57:32 +000041 double dd = s.doubleValue();
Stuart McCulloch2286f232012-06-15 13:27:53 +000042
Stuart McCullochbb014372012-06-07 21:57:32 +000043 if (type == double.class || type == Double.class)
44 return s.doubleValue();
45
Stuart McCulloch2286f232012-06-15 13:27:53 +000046 if ((type == int.class || type == Integer.class) && within(dd, Integer.MIN_VALUE, Integer.MAX_VALUE))
Stuart McCullochbb014372012-06-07 21:57:32 +000047 return s.intValue();
48
49 if ((type == long.class || type == Long.class) && within(dd, Long.MIN_VALUE, Long.MAX_VALUE))
50 return s.longValue();
51
52 if ((type == byte.class || type == Byte.class) && within(dd, Byte.MIN_VALUE, Byte.MAX_VALUE))
53 return s.byteValue();
54
Stuart McCulloch2286f232012-06-15 13:27:53 +000055 if ((type == short.class || type == Short.class) && within(dd, Short.MIN_VALUE, Short.MAX_VALUE))
Stuart McCullochbb014372012-06-07 21:57:32 +000056 return s.shortValue();
57
58 if (type == float.class || type == Float.class)
59 return s.floatValue();
60
61 if (type == BigDecimal.class)
62 return BigDecimal.valueOf(dd);
63
64 if (type == BigInteger.class)
65 return BigInteger.valueOf(s.longValue());
66
67 throw new IllegalArgumentException("Unknown number format: " + type);
68 }
69
70 private boolean within(double s, double minValue, double maxValue) {
71 return s >= minValue && s <= maxValue;
72 }
73}