Generic Protostuffserializer for Java

Source: Internet
Author: User

It was cumbersome to use protobuf or Protostuff before, and each class was individually customized, encapsulating a class.

Colleagues have tested performance and compression rates well, especially compared to JSON serialization.

Note: Only the Pojo class is supported (that is, there is a need for the Get/set method), the first call to a new class is initialized with a register time of one hundred or two hundred milliseconds, and soon thereafter.

ImportIo.protostuff.LinkedBuffer;ImportIo.protostuff.ProtostuffIOUtil;ImportIo.protostuff.Schema;ImportIo.protostuff.runtime.RuntimeSchema;Importjava.io.Serializable;ImportJava.util.Map;ImportJava.util.concurrent.ConcurrentHashMap;/*** Protostuff Serializer Tool, for POJO serialization. * Protostuff are much more efficient than JSON, even faster than Protobuf and Avro, but the serialized string is human-unreadable. * Not the support Array or generic-type, please wrap these special objects via a POJO with empty constructors. * * @authorLHFCWS *@since2016-03-16*/ Public classProtostuffserializerImplementsSerializable {StaticMap<class, schema> SchemaCache =NewConcurrenthashmap<>(); /*** Common Protostuff Serialize, object need a empty constructor * be careful to convert result byte[] to Stri     Ng, use new String (bytes, standardcharsets.utf_16le). *     * @paramobj *@param<T> *@return     */     Public Static<T>byte[] serializeobject (T obj) {Class<T> Klass = (class<t>) Obj.getclass (); Linkedbuffer Buffer= Linkedbuffer.allocate (4096); if(Schemacache.containskey (Klass)) {returnProtostuffioutil.tobytearray (obj, Schemacache.get (Klass), buffer); } Else{schemacache.put (Klass, Runtimeschema.getschema (Klass)); returnProtostuffioutil.tobytearray (obj, Schemacache.get (Klass), buffer); }    }    /*** Common Protostuff unserialize * *@paramBS *@paramKlass *@param<T> *@return     */     Public Static<T> T Deserialize (byte[] BS, class<t>Klass) {        if(Schemacache.containskey (Klass)) {Schema<T> schema =Schemacache.get (Klass); T msg=Schema.newmessage ();            Protostuffioutil.mergefrom (BS, MSG, schema); returnmsg; } Else{Schema<T> schema =Runtimeschema.getschema (Klass); T msg=Schema.newmessage ();            Schemacache.put (Klass, schema);            Protostuffioutil.mergefrom (BS, MSG, schema); returnmsg; }    }}

Use Demo:

//if the Pojo class is called directly, the non-Pojo class reference is as follows: (assuming there is already a Strparams model class)     Public Static classStrparamspojo {PrivateStrparams p;  PublicStrparamspojo () {} PublicStrparamspojo (Strparams p) { This. P =p; }         Publicstrparams Getp () {returnp; }         Public voidSetp (Strparams p) { This. P =p; }     }     Public voidSerialize ()throwsIOException {strparams P=NewStrparams (); Strparamspojo Pojo=NewStrparamspojo (P); byte[] bs =Protostuffserializer.serializeobject (Pojo); }     Public voidDeserialize (byte[] BS)throwsIOException {Strparamspojo Pojo= Protostuffserializer.deserialize (BS, Strparamspojo.class); Strparams P=Pojo.getp (); }

Comes with a fastjsonserializer:

ImportCom.alibaba.fastjson.JSON;Importcom.alibaba.fastjson.serializer.SerializerFeature;ImportJava.lang.reflect.Type;/*** Fastjson is faster than Gson. * But do remember your objects have get/set for the ' Fields ' want to serialze. * @authorLHFCWS*/ Public classFastjsonserializer {/*** Serializes the given object into a JSON string *@paramobj Given object *@returnJSON string after object serialization*/     Public Static<T>String Serialize (T obj) {returnjson.tojsonstring (obj, Serializerfeature.ignorenonfieldgetter, serializerfeature.skiptr Ansientfield, Serializerfeature.disablecircularreferencedetect, serializerfeature.browsercom    patible); }     Public Static<T>String serializepretty (T obj) {returnjson.tojsonstring (obj, Serializerfeature.ignorenonfieldgetter, serializerfeature.skiptr Ansientfield, Serializerfeature.disablecircularreferencedetect, serializerfeature.browsercom    Patible, Serializerfeature.prettyformat); }    /*** Deserialize JSON string into entity class object According to the class name *@paramJSON string to deserialize JSON *@paramKlass deserialized entity class *@returndeserialized Object*/     Public Static<T> T Deserialize (String JSON, class<t>Klass) {        returnJson.parseobject (JSON, Klass); }    /*** Deserializes the JSON string into an entity class object that implements the type interface *@paramJSON string to deserialize JSON *@paramType Generic Types *@returndeserialized Object*/     Public Static<T>T Deserialize (String json, type type) {returnjson.parseobject (JSON, type); }}

Common Protostuffserializer for Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.