|
| 1 | +package com.jsoniter.datetime; |
| 2 | + |
| 3 | +import com.jsoniter.JsonException; |
| 4 | +import com.jsoniter.JsonIterator; |
| 5 | +import com.jsoniter.any.Any; |
| 6 | +import com.jsoniter.output.JsonStream; |
| 7 | +import com.jsoniter.spi.Decoder; |
| 8 | +import com.jsoniter.spi.Encoder; |
| 9 | +import com.jsoniter.spi.JsoniterSpi; |
| 10 | + |
| 11 | +import java.io.IOException; |
| 12 | +import java.text.ParseException; |
| 13 | +import java.text.SimpleDateFormat; |
| 14 | +import java.util.Date; |
| 15 | + |
| 16 | +/** |
| 17 | + * this is just an example |
| 18 | + */ |
| 19 | +public class JdkDatetimeSupport { |
| 20 | + |
| 21 | + private static String pattern; |
| 22 | + private final static ThreadLocal<SimpleDateFormat> sdf = new ThreadLocal<SimpleDateFormat>() { |
| 23 | + @Override |
| 24 | + protected SimpleDateFormat initialValue() { |
| 25 | + return new SimpleDateFormat(pattern); |
| 26 | + } |
| 27 | + }; |
| 28 | + |
| 29 | + public static void enable(String pattern) { |
| 30 | + JdkDatetimeSupport.pattern = pattern; |
| 31 | + JsoniterSpi.registerTypeEncoder(Date.class, new Encoder() { |
| 32 | + @Override |
| 33 | + public void encode(Object obj, JsonStream stream) throws IOException { |
| 34 | + stream.writeVal(sdf.get().format(obj)); |
| 35 | + } |
| 36 | + |
| 37 | + @Override |
| 38 | + public Any wrap(Object obj) { |
| 39 | + return Any.wrap(sdf.get().format(obj)); |
| 40 | + } |
| 41 | + }); |
| 42 | + JsoniterSpi.registerTypeDecoder(Date.class, new Decoder() { |
| 43 | + @Override |
| 44 | + public Object decode(JsonIterator iter) throws IOException { |
| 45 | + try { |
| 46 | + return sdf.get().parse(iter.readString()); |
| 47 | + } catch (ParseException e) { |
| 48 | + throw new JsonException(e); |
| 49 | + } |
| 50 | + } |
| 51 | + }); |
| 52 | + } |
| 53 | +} |
0 commit comments