JSON(JavaScript Object Notation) 是一種輕量級的數據交換格式。 易於人閱讀和編寫。同時也易於機器解析和生成。 它基於JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一個子集。 JSON採用徹底獨立於語言的文本格式,這些特性使JSON成爲理想的數據交換語言。javascript
下面介紹四款處理json的java類庫:Json-lib、Gson、Jackson、Fastjsonhtml
JSON-lib is a java library for transforming beans, maps, collections, java arrays and XML to JSON and back again to beans and DynaBeans. 官網:http://json-lib.sourceforge.net/java
maven依賴配置:git
<dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency>
示例:github
/** * 將對象序列化成json字符串 * @param obj * @return */ public static String bean2Json(Object obj){ JSONObject jsonObject=JSONObject.fromObject(obj); return jsonObject.toString(); } /** * 將json字符串反序列化爲對象 * @param jsonStr * @param objClass 反序列化爲該類的對象 * @return */ @SuppressWarnings("unchecked") public static <T> T json2Bean(String jsonStr,Class<T> objClass){ return (T)JSONObject.toBean(JSONObject.fromObject(jsonStr), objClass); }
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.json
官網:https://code.google.com/p/google-gson/app
maven依賴:maven
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.2.4</version> </dependency>
示例:ide
public static String bean2Json(Object obj){ Gson gson = new GsonBuilder().create(); return gson.toJson(obj); } public static <T> T json2Bean(String jsonStr,Class<T> objClass){ Gson gson = new GsonBuilder().create(); return gson.fromJson(jsonStr, objClass); } /** * 把混亂的json字符串整理成縮進的json字符串 * @param uglyJsonStr * @return */ 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; }
Jackson is a high-performance JSON processor (parser, generator)。官網:http://jackson.codehaus.org/Home性能
maven依賴:
<dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency>
示例:
public static String bean2Json(Object obj) throws IOException { ObjectMapper mapper = new ObjectMapper(); StringWriter sw = new StringWriter(); JsonGenerator gen = new JsonFactory().createJsonGenerator(sw); mapper.writeValue(gen, obj); gen.close(); return sw.toString(); } public static <T> T json2Bean(String jsonStr, Class<T> objClass) throws JsonParseException, JsonMappingException, IOException { ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(jsonStr, objClass); }
Fastjson是一個Java語言編寫的JSON處理器,由阿里巴巴公司開發。網址:https://github.com/alibaba/fastjson
maven依賴配置:
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.35</version> </dependency>
示例:
public static String bean2Json(Object obj){ return JSON.toJSONString(obj); } public static <T> T json2Bean(String jsonStr,Class<T> objClass){ return JSON.parseObject(jsonStr, objClass); }
一、Java對象序列化爲Json字符串:
執行100 0000次轉換,各個類庫的耗時以下:(以秒爲單位)
Gson | 48.891s |
Json-lib | 311.446s |
Jackson | 19.439s |
FastJson | 21.706 |
二、Json字符串 反序列化爲Java對象
執行100 0000次轉換,各個類庫的耗時以下:(以秒爲單位)
Gson | 39.280s |
Json-lib | 使用該類庫的方法進行轉換時(測試代碼見下面),拋出異常。其緣由是Person類的屬性:List<Person> friends,其List中的對象不是Person類型的對象,而是net.sf.ezmorph.bean.MorphDynaBean類型的對象。說明,Json-lib對嵌套的自定義類支持的不好,或許是我寫的方法有問題。 |
Jackson | 26.427s |
FastJson | 40.556 |
三、總結:
Java Bean序列化爲Json,性能:Jackson > FastJson > Gson > Json-lib。這4中類庫的序列化結構都正確。
Json字符串反序列化爲Java Bean時,性能:Jackson > Gson > FastJson >Json-lib。而且Jackson、Gson、FastJson能夠很好的支持複雜的嵌套結構定義的類,而Json-lib對於複製的反序列化會出錯。
Jackson、FastJson、Gson類庫各有優勢,各有本身的專長,都具備很高的可用性。
四、測試用例
1)Java Bean
public class Person { private String name; private FullName fullName; private int age; private Date birthday; private List<String> hobbies; private Map<String, String> clothes; private List<Person> friends; //getter setter 方法。略 @Override public String toString() { String str= "Person [name=" + name + ", fullName=" + fullName + ", age=" + age + ", birthday=" + birthday + ", hobbies=" + hobbies + ", clothes=" + clothes + "]\n"; if(friends!=null){ str+="Friends:\n"; for (Person f : friends) { str+="\t"+f; } } return str; } } class FullName { private String firstName; private String middleName; private String lastName;
//構造方法、getter setter 方法,略 @Override public String toString() { return "[firstName=" + firstName + ", middleName=" + middleName + ", lastName=" + lastName + "]"; } }
2)Json-lib、Gson、Jackson、FastJson類庫:
import net.sf.json.JSONObject; public class JsonObjectUtil { public static String bean2Json(Object obj){ JSONObject jsonObject=JSONObject.fromObject(obj); return jsonObject.toString(); } @SuppressWarnings("unchecked") public static <T> T json2Bean(String jsonStr,Class<T> objClass){ return (T)JSONObject.toBean(JSONObject.fromObject(jsonStr), objClass); } }
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonParser; public class GsonUtil { 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; } }
import java.io.IOException; import java.io.StringWriter; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; public class JacksonUtil { private static ObjectMapper mapper = new ObjectMapper(); public static String bean2Json(Object obj) throws IOException { StringWriter sw = new StringWriter(); JsonGenerator gen = new JsonFactory().createJsonGenerator(sw); mapper.writeValue(gen, obj); gen.close(); return sw.toString(); } public static <T> T json2Bean(String jsonStr, Class<T> objClass) throws JsonParseException, JsonMappingException, IOException { return mapper.readValue(jsonStr, objClass); } }
public class FastJsonUtil { public static String bean2Json(Object obj){ return JSON.toJSONString(obj); } public static <T> T json2Bean(String jsonStr,Class<T> objClass){ return JSON.parseObject(jsonStr, objClass); } }
3)Java對象序列化爲Json字符串 測試類:
public class TestBean2Json { private Person p; private Person createAPerson(String name,List<Person> friends) { Person newPerson=new Person(); 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; } @Before public void init(){ List<Person> friends=new ArrayList<Person>(); friends.add(createAPerson("小明",null)); friends.add(createAPerson("Tony",null)); friends.add(createAPerson("陳小二",null)); p=createAPerson("邵同窗",friends); } // @Test public void testGsonBean2Json(){ System.out.println(GsonUtil.bean2Json(p)); for (int i = 0; i < 1000000; i++) { GsonUtil.bean2Json(p); } } //@Test public void testJsonObjectBean2Json(){ System.out.println(JsonlibUtil.bean2Json(p)); for (int i = 0; i < 1000000; i++) { JsonlibUtil.bean2Json(p); } } // @Test public void testJacksonBean2Json() throws Exception{ System.out.println(JacksonUtil.bean2Json(p)); for (int i = 0; i < 1000000; i++) { JacksonUtil.bean2Json(p); } } @Test public void testFastJsonBean2Json() throws Exception{ System.out.println(FastJsonUtil.bean2Json(p)); for (int i = 0; i < 1000000; i++) { FastJsonUtil.bean2Json(p); } } }
4)Json字符串 反序列化爲Java對象 測試類:
public class TestJson2Bean { private String jsonStr; @Before public void init(){ jsonStr="{\"name\":\"邵同窗\",\"fullName\":{\"firstName\":\"xxx_first\",\"middleName\":\"xxx_middle\",\"lastName\":\"xxx_last\"},\"age\":24,\"birthday\":null,\"hobbies\":[\"籃球\",\"游泳\",\"coding\"],\"clothes\":{\"shoes\":\"安踏\",\"trousers\":\"adidas\",\"coat\":\"Nike\"},\"friends\":[{\"name\":\"小明\",\"fullName\":{\"firstName\":\"xxx_first\",\"middleName\":\"xxx_middle\",\"lastName\":\"xxx_last\"},\"age\":24,\"birthday\":null,\"hobbies\":[\"籃球\",\"游泳\",\"coding\"],\"clothes\":{\"shoes\":\"安踏\",\"trousers\":\"adidas\",\"coat\":\"Nike\"},\"friends\":null},{\"name\":\"Tony\",\"fullName\":{\"firstName\":\"xxx_first\",\"middleName\":\"xxx_middle\",\"lastName\":\"xxx_last\"},\"age\":24,\"birthday\":null,\"hobbies\":[\"籃球\",\"游泳\",\"coding\"],\"clothes\":{\"shoes\":\"安踏\",\"trousers\":\"adidas\",\"coat\":\"Nike\"},\"friends\":null},{\"name\":\"陳小二\",\"fullName\":{\"firstName\":\"xxx_first\",\"middleName\":\"xxx_middle\",\"lastName\":\"xxx_last\"},\"age\":24,\"birthday\":null,\"hobbies\":[\"籃球\",\"游泳\",\"coding\"],\"clothes\":{\"shoes\":\"安踏\",\"trousers\":\"adidas\",\"coat\":\"Nike\"},\"friends\":null}]}"; } // @Test public void testGsonjson2Bean() throws Exception{ Person pp=GsonUtil.json2Bean(jsonStr, Person.class); System.out.println(pp); for (int i = 0; i < 1000000; i++) { GsonUtil.json2Bean(jsonStr, Person.class); } } // @Test public void testJsonlibJson2Bean() throws Exception{ Person pp=JsonlibUtil.json2Bean(jsonStr, Person.class); System.out.println(pp); for (int i = 0; i < 1000000; i++) { JsonlibUtil.json2Bean(jsonStr, Person.class); } } // @Test public void testJacksonJson2Bean() throws Exception{ Person pp=JacksonUtil.json2Bean(jsonStr, Person.class); System.out.println(pp); for (int i = 0; i < 1000000; i++) { JacksonUtil.json2Bean(jsonStr, Person.class); } } @Test public void testFastJsonJson2Bean() throws Exception{ Person pp=FastJsonUtil.json2Bean(jsonStr, Person.class); System.out.println(pp); for (int i = 0; i < 1000000; i++) { FastJsonUtil.json2Bean(jsonStr, Person.class); } } }