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) + " 笔/秒")); } }
时间: 2024-10-08 12:23:12