Jackson VS FastJson VS Gson

來源:互聯網
上載者:User

標籤:des   io   ar   os   sp   for   java   on   資料   

package com.dj.json.model;import java.util.Date;import java.util.List;import java.util.Map;public 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();public 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 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 工具類 * @version Ver 1.0 * @author <a href="mailto:[email protected]">dejianliu</a> * @Date 2013-4-23 下午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);public static ConcurrentLinkedQueue<ObjectMapper> mapperQueue = new ConcurrentLinkedQueue<ObjectMapper>();public 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串轉換為Java泛型對象,可以是各種類型,此方法最為強大。用法看測試案例。 *  * @param <T> * @param jsonString *            JSON字串 * @param tr *            TypeReference,例如: new TypeReference< List<FamousUser> >(){} * @return 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, tr);} catch (Exception e) { e.printStackTrace();} finally {returnMapper(mapper);}}return null;}/** * Json字串轉Java對象 *  * @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對象轉Json字串 *  * @param object *            目標對象 * @param executeFields *            排除欄位 * @param includeFields *            包含欄位 * @param dateFormat *            時間格式化 * @param isPretty *            是否格式化列印 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 com.dj.json.utils.jackson.JacksonUtils;import com.dj.json.utils.jackson.JsonUtils;/** *GSON 序列化:1000000 筆資料  cost :21587 毫秒  平均:46324.176587761154 筆/秒 *JACKSON 序列化:1000000 筆資料  cost :9284 毫秒  平均:107712.19302024988 筆/秒 *FastJSON 序列化:1000000 筆資料  cost :9180 毫秒  平均:108932.46187363834 筆/秒 * @version : Ver 1.0 * @author: <a href="mailto:[email protected]">liudejian</a> * @date: 2014-12-10 上午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("籃球");hobbies.add("遊泳");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", "安踏");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("小明", null));friends.add(createAPeople("Tony", null));friends.add(createAPeople("陳小二", null));p = createAPeople("邵同學", 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("序列化:"+ num+ " 筆資料  cost :"+ dif+ " 毫秒 "+ " 平均:"+ (Double.valueOf(num)/ Double.valueOf(Double.valueOf(dif) / 1000) + " 筆/秒"));}}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   還原序列化:1000000 筆資料  cost :21456 毫秒  平均:46607.00969425802 筆/秒 *JACKSON  還原序列化:1000000 筆資料  cost :13362 毫秒  平均:74839.095943721 筆/秒  *FastJSON  還原序列化:1000000 筆資料  cost :36814 毫秒  平均:27163.579073178684 筆/秒 * @version : Ver 1.0 * @author: <a href="mailto:[email protected]">liudejian</a> * @date: 2014-12-10 上午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("籃球");hobbies.add("遊泳");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", "安踏");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("小明", null));friends.add(createAPerson("Tony", null));friends.add(createAPerson("陳小二", null));p = createAPerson("邵同學", 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("還原序列化:"+ num+ " 筆資料  cost :"+ dif+ " 毫秒 "+ " 平均:"+ (Double.valueOf(num)/ Double.valueOf(Double.valueOf(dif) / 1000) + " 筆/秒"));}}



Jackson VS FastJson VS Gson

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.