Convert 组件介绍
Convert 是一个比较独立的组件,仅依赖于util包。提供Java对象的序列化与反解析功能。支持JSON(JavaScript Object Notation)、BSON(Binary Stream Object Notation)两种格式化。 两种格式使用方式完全一样,其性能都大幅度超过其他JSON框架。
Convert 快速上手
本介绍仅以JSON为例(BSON与JSON使用方式雷同)。其操作类主要是JsonConvert,配置类主要是JsonFactory、ConvertColumn。
JsonConvert 序列化方法:
public String convertTo(Object value);
public String convertTo(final Type type, Object value);
public void convertTo(final JsonWriter out, Object value);
public void convertTo(final JsonWriter out, final Type type, Object value);
public ByteBuffer[] convertTo(final Supplier<ByteBuffer> supplier, final Type type, Object value);
public ByteBuffer[] convertTo(final Charset charset, final Supplier<ByteBuffer> supplier, final Type type, Object value);
public ByteBuffer[] convertTo(final Supplier<ByteBuffer> supplier, Object value);
public ByteBuffer[] convertTo(final Charset charset, final Supplier<ByteBuffer> supplier, Object value);
JsonConvert 反解析方法:
public <T> T convertFrom(final Type type, final String text);
public <T> T convertFrom(final Type type, final char[] text);
public <T> T convertFrom(final Type type, final char[] text, int start, int len);
public <T> T convertFrom(final Type type, final ByteBuffer... buffers);
public static void main(String[] args) throws Exception {
JsonFactory factory = JsonFactory.root();
factory.setTiny(true);
final JsonConvert convert = JsonFactory.root().getConvert();
String json = "{\"access_token\":\"vVX2bIjN5P9TMOphDkStM96eNWapAehTuWAlVDO74aFaYxLwj2b-9-T9p_W2mfr9\",\"expires_in\":7200, \"aa\":\"\"}";
Map<String, String> map = convert.convertFrom(JsonConvert.TYPE_MAP_STRING_STRING, json);
System.out.println(map);
System.out.println(convert.convertTo(map));
ByteBuffer[] buffers = convert.convertTo(() -> ByteBuffer.allocate(1024), map);
byte[] bs = new byte[buffers[0].remaining()];
buffers[0].get(bs);
System.out.println(new String(bs));
main2(args);
}