Package com.dj.json.model;import java.util.date;import java.util.list;import java.util.map ;p ublic class people {private string name;private fullname fullname;private int age;private Date birthday;private List<String> hobbies;private map<string, string> clothes;private list<people> friends; // auto get set}public class fullname { private string firstname;private string middlename;private string lastname; // auto get set}package com.dj.json.utils.fastjson;import Com.alibaba.fastjson.json;import com.alibaba.fastjson.serializer.serializerfeature;public class fastjsonutils {public static string bean2json (object obj) { return json.tojsonstring (obj);} public static String bean2json (Object obj,string dateformat) {return Json.tojsonstringwithdateformat (Obj, dateformat, serializerfeature.prettyformat); }public Static <t> t json2bean (String jsonstr, class<t> objclass) { Return json.parseobject (Jsonstr, objclass);}} public class gsonutils {private static gson gson = new Gsonbuilder (). Create ();p Ublic static string bean2json (object obj) {return Gson.tojson (obj);} Public static <t> t json2bean (String jsonstr, class<t> objclass ) {return gson.fromjson (Jsonstr, objclass);} Public static string jsonformatter (STRING&NBSP;UGLYJSONSTR) {Gson gson = New gsonbuilder (). setprettyprinting (). Create (); Jsonparser jp = new jsonparser (); Jsonelement je = jp.parse (UGLYJSONSTR); String prettyjsonstring = gson.tojson (JE); return prettyjsonstring;}} package com.dj.json.utils.jackson;import java.nio.charset.charset;import java.text.simpledateformat;import java.util.concurrent.concurrentlinkedqueue;import org.apache.commons.lang.stringutils;import org.codehaus.jackson.map.deserializationconfig;import Org.codehaus.jackson.map.objectmapper;import org.codehaus.jackson.map.ser.stdserializerprovider;import org.codehaus.jackson.map.ser.impl.SimpleBeanPropertyFilter;import org.codehaus.jackson.map.ser.impl.simplefilterprovider;import org.codehaus.jackson.map.ser.std.nullserializer;import org.codehaus.jackson.type.typereference;/** * @description: jsonutils Tools * @version Ver 1.0 * @author <a href= "mailto:[email protected" >dejianliu</a> * @Date 2013-4-23 Afternoon 12:32:29 */public class JsonUtils {private static final Charset DEFAULT_CHARSET = Charset.forname ("UTF-8"); static boolean ispretty = false;private static final String DEFAULT_DATE_FORMAT = "Yyyy-mm-dd hh:mm:ss"; static stdserializerprovider sp = new stdserializerprovider (); Static {sp.setnullvalueserializer ( nullserializer.instance);} static simpledateformat defaultdateformat = new simpledateformat (DEFAULT_DATE_ FORMAT);p Ublic static concurrentlinkedqueue<objectmapper> mapperqueue = new ConcurrentLinkedQueue<ObjectMapper> ();p ublic static objectmapper getobjectmapper () {objectmapper mapper = mapperqueue.poll (); if (mapper == null) {mapper = new objectmapper (null, sp, null);} Return mapper;} Public static void returnmapper (ObJectmapper mapper) {if (mapper != null) {mapperqueue.offer (mapper);}} Public static boolean ispretty () {return ispretty;} Public static void setpretty (Boolean ispretty) {JsonUtils.isPretty = Ispretty;} /** * json strings are converted to Java generic objects, which can be of various types, and this method is the most powerful. usage See test cases. * * @param <T> * @param jsonString * json Strings * @param tr * typereference, such as: new typereference< List<FamousUser> > () {} * @return list Object list */@SuppressWarnings (" Unchecked ") Public static <t> t json2genericobject (string jsonstring, Typereference<t> tr, string dateformat) {if (Stringutils.isnotempty (jsonString) ) {objectmapper Mapper = getobjectmapper (); try {//objectmapper objectmapper = new Objectmapper (Null, sp, null); Mapper.disable (DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES ); if (Stringutils.isblank (DateFormat)) {mapper.setdateformat (Defaultdateformat);} else {SimpleDateFormat sdf = (SimpleDateFormat) defaultdateformat.clone (); Sdf.applypattern (DateFormat); Mapper.setdateformat (SDF); }return (T) mapper.readvalue (jsonString , &NBSP;TR);} catch (exception e) { e.printstacktrace ();} finally {returnmapper (mapper);}} Return null;} /** * json string to Java object * * @param jsonString * @param c * @return */public static <t> t json2object (string jsonstring, Class<t> c,string dateformat) {if (Stringutils.isnotempty (jsonstring)) {ObjectMapper mapper = getobjectmapper (); try {//objectmapper objectmapper = New objectmapper (Null, sp, null); Mapper.disable (DeserializationConfig.Feature.FAIL_ON_UNKNOWN_ PROPERTIES); if (Stringutils.isblank (DateFormat)) {mapper.setdateformat (Defaultdateformat);} else {SimpleDateFormat sdf = (SimpleDateFormat) defaultdateformat.clone (); Sdf.applypattern (DateFormat); Mapper.setdateformat (SDF);} return (T) mapper.readvalue (jsonstring, c);} catch (exception e) {e.printstacktrace ();} finally {returnmapper (mapper);}} Return null;} /** * java object to JSON string * * @param object * target Objects * @param executeFields * exclude fields * @param includefields * contains fields * @param dateformat * time formatting * @param ispretty * whether to format print default false * @return */public static string tojson (object object, string[] Executefields,string[] includefields, string dateformat) {string jsonstring = ""; Objectmapper mapper = getobjectmapper (); try {bidbeanserializerfactory bidbeanfactory = bidbeanserializerfactory.instance;if (Stringutils.isblank (dateFormat)) { Mapper.setdateformat (Defaultdateformat);} else {SimpleDateFormat sdf = (SimpleDateFormat) defaultdateformat.clone (); Sdf.applypattern (DateFormat); Mapper.setdateformat (SDF);} if (includefields != null) {String filterId = "Includefilter"; Mapper.setfilters (New simplefilterprovider (). AddFilter (Filterid, simplebeanpropertyfilter.filteroutallexcept (Includefields))); Bidbeanfactory.setfilterid (Filterid); mapper.setserializerfactory (bidbeanfactory);} else if (Includefields == null && executefields != null) {String filterId = "Executefilter"; Mapper.setfilters (New simplefilterprovider (). AddFilter (Filterid, simplebeanpropertyfilter.serializeallexcept (Executefields))); Bidbeanfactory.setfilterid (Filterid); mapper.setserializerfactory (bidbeanfactory);} if (Ispretty) {jsonstring = mapper.writerwithdefaultprettyprinter (). Writevalueasstring (object);} else {jsonstring = mapper.writevalueasstring (object);}} catch (exception e) {e.printstacktrace ();} finally {returnmapper (mapper);} return jsonstring;} }package com.dj.json.test;import java.util.arraylist;import java.util.hashmap;import java.util.list;import java.util.map;import com.dj.json.model.fullname;import com.dj.json.model.people;import com.dj.json.utils.fastjson.fastjsonutils;import Serialization of com.dj.json.utils.jackson.jacksonutils;import com.dj.json.utils.jackson.jsonutils;/** *gson :1000000 pen Data cost :21587 milliseconds average:46324.176587761154 pen/sec *jackson Serializing:1000000 pen data cost :9284 milliseconds average:107712.19302024988 pen/sec * fastjson serializing:1000000 pen data cost :9180 milliseconds average:108932.46187363834 pen/ SEC * @version : Ver 1.0 * @author: <a href= "mailto:[email Protected] ">liudejian</a> * @date: 2014-12-10 Morning 10:50:27 */public class JsonSer {private static People p;Private static int num = 1000000;private static people createapeople ( String name, list<people> friends) {People newPeople = new People (); Newpeople.setname (name); Newpeople.setfullname (New fullname ("Xxx_first", "Xxx_middle", "xxx_ Last ")); Newpeople.setage (24); List<string> hobbies = new arraylist<string> (); Hobbies.add ("basketball"); Hobbies.add (" Swimming "); Hobbies.add (" coding "); Newpeople.sethobbies (hobbies); Map<string, string> clothes = new hashmap<string, string> (); Clothes.put ("coat", "Nike"), Clothes.put ("trousers", "Adidas"), Clothes.put ("Shoes", "Anta"); Newpeople.setclothes (clothes); Newpeople.setfriends (friends); return newpeople;} Public static void main (String[] args) throws Exception {List<People> friends = new ArrayList<People> (); Friends.add (CreateapeOple ("Xiaoming", null)), Friends.add (Createapeople ("Tony", null)), Friends.add (Createapeople ("Chen Xiao", NULL));p = createapeople ("Shao classmate", friends);long starttime = System.currenttimemillis ();for (int i = 0; i < num; i++) {// Gsonutils.bean2json (P);// jacksonutils.bean2json (P); Jsonutils.tojson (p,null, null, "Yyyy-mm-dd");// fastjsonutils.bean2json (P, "Yyyy-MM-dd");} Long endtime = system.currenttimemillis ();long dif = endtime - StartTime; System.out.println ("Serialization: + num+ " pen data cost : "+ dif+ " milliseconds "+ " Average:" + (double.valueof (num)/ double.valueof (double.valueof (DIF) / 1000) + " PEN/sec");}} import java.util.arraylist;import java.util.hashmap;import java.util.list;import Java.util.map;import com.dj.json.model.fullname;import com.dj.json.modEl. people;import com.dj.json.utils.jackson.jsonutils;/** *gson deserialization of:1000000 pen data cost :21456 milliseconds Average:46607.00969425802 pen/sec *JACKSON deserialization :1000000 pen Data cost :13362 milliseconds average:74839.095943721 pen/sec * fastjson deserializing:1000000 pen data cost :36814 milliseconds average: 27163.579073178684 PEN/sec * @version : Ver 1.0 * @author: <a href= "mailto:[ Email protected] ">liudejian</a> * @date: 2014-12-10 Morning 10:50:27 */public class jsondesc {private static people p;private static int num = 1000000;private static people createaperson (string name, list<people > friends) {people newperson = new people (); Newperson.setname (name); Newperson.setfullname (new fUllname ("Xxx_first", "Xxx_middle", "Xxx_last")); Newperson.setage (24); List<string> hobbies = new arraylist<string> (); Hobbies.add ("basketball"); Hobbies.add (" Swimming "); Hobbies.add (" coding "); Newperson.sethobbies (hobbies); Map<string, string> clothes = new hashmap<string, string> (); Clothes.put ("coat", "Nike"), Clothes.put ("trousers", "Adidas"), Clothes.put ("Shoes", "Anta"); Newperson.setclothes (clothes); Newperson.setfriends (friends); Return newperson;} Public static void main (String[] args) throws Exception {List<People> friends = new ArrayList<People> (Friends.add) (Createaperson ("Xiao Ming", null)); Friends.add (Createaperson ("Tony", null)), Friends.add (Createaperson ("Chen Xiao", null));p = Createaperson ("Shao classmate", friends); String jsonstr = jsonutils.tojson (P, null, null, null); System.out.println ( JsonstR); Long starttime = system.currenttimemillis ();for (int i = 0; i < num; i++) {////gsonutils.json2bean (Jsonstr, people.class); Jsonutils.json2object (jsonstr, people.class, "Yyyy-mm-dd");//jacksonutils.json2bean (jsonStr, People.class);// fastjsonutils.json2bean (Jsonstr, people.class);} Long endtime = system.currenttimemillis ();long dif = endtime - StartTime; System.out.println ("Deserialization: + num+ " pen data cost : "+ dif+ " milliseconds " + " Average:" + (double.valueof (num)/ double.valueof (double.valueof (DIF) / 1000) + " PEN/S"));}}
Jackson vs Fastjson vs Gson