|
| 1 | +package com.jsoniter.extra; |
| 2 | + |
| 3 | +import com.jsoniter.JsonException; |
| 4 | +import com.jsoniter.any.Any; |
| 5 | +import com.jsoniter.output.JsonStream; |
| 6 | +import com.jsoniter.spi.Encoder; |
| 7 | +import com.jsoniter.spi.JsoniterSpi; |
| 8 | + |
| 9 | +import java.io.IOException; |
| 10 | + |
| 11 | +/** |
| 12 | + * default float/double encoding will keep 6 decimal places |
| 13 | + * enable precise encoding will use JDK toString to be precise |
| 14 | + */ |
| 15 | +public class PreciseFloatSupport { |
| 16 | + private static boolean enabled; |
| 17 | + |
| 18 | + public static synchronized void enable() { |
| 19 | + if (enabled) { |
| 20 | + throw new JsonException("PreciseFloatSupport.enable can only be called once"); |
| 21 | + } |
| 22 | + enabled = true; |
| 23 | + JsoniterSpi.registerTypeEncoder(Double.class, new Encoder() { |
| 24 | + @Override |
| 25 | + public void encode(Object obj, JsonStream stream) throws IOException { |
| 26 | + stream.writeRaw(obj.toString()); |
| 27 | + } |
| 28 | + |
| 29 | + @Override |
| 30 | + public Any wrap(Object obj) { |
| 31 | + Double number = (Double) obj; |
| 32 | + return Any.wrap(number.doubleValue()); |
| 33 | + } |
| 34 | + }); |
| 35 | + JsoniterSpi.registerTypeEncoder(double.class, new Encoder.DoubleEncoder() { |
| 36 | + @Override |
| 37 | + public void encodeDouble(double obj, JsonStream stream) throws IOException { |
| 38 | + stream.writeRaw(Double.toString(obj)); |
| 39 | + } |
| 40 | + }); |
| 41 | + JsoniterSpi.registerTypeEncoder(Float.class, new Encoder() { |
| 42 | + @Override |
| 43 | + public void encode(Object obj, JsonStream stream) throws IOException { |
| 44 | + stream.writeRaw(obj.toString()); |
| 45 | + } |
| 46 | + |
| 47 | + @Override |
| 48 | + public Any wrap(Object obj) { |
| 49 | + Float number = (Float) obj; |
| 50 | + return Any.wrap(number.floatValue()); |
| 51 | + } |
| 52 | + }); |
| 53 | + JsoniterSpi.registerTypeEncoder(float.class, new Encoder.FloatEncoder() { |
| 54 | + @Override |
| 55 | + public void encodeFloat(float obj, JsonStream stream) throws IOException { |
| 56 | + stream.writeRaw(Float.toString(obj)); |
| 57 | + } |
| 58 | + }); |
| 59 | + } |
| 60 | +} |
0 commit comments