一、前言
基于alibaba的com.alibaba.fastjson.JSONObject(fastjson-1.1.2.jar.zip)实现json对象的二进制序列化serialize和反序列化deserialize,下面自定义FastJsonSerialization类实现整个过程,代码如下
import java.nio.charset.Charset;@b@import com.alibaba.fastjson.JSONObject;@b@@b@public class FastJsonSerialization implements Serialization {@b@@b@ @b@ private Charset charset;@b@ @b@ public FastJsonSerialization(){@b@ charset=Charset.forName("UTF-8");@b@ }@b@ @b@ public FastJsonSerialization(Charset charset){@b@ this.charset=charset;@b@ }@b@ @b@ @Override@b@ public Object deserialize(Class<?> clazz, byte[] bytes) {@b@ String data=new String(bytes,charset);@b@ return JSONObject.parseObject(data, clazz);@b@ }@b@@b@ @Override@b@ public byte[] serialize(Object value) {@b@ return JSONObject.toJSONString(value).getBytes(charset);@b@ }@b@@b@ @b@ public void setCharset(String charset) {@b@ this.charset = Charset.forName(charset);@b@ }@b@ @b@}