JSON (JavaScript Object Notation) is a lightweight data interchange format. Easy to read and write. Also easy for machines to parse and generate. It is based on JavaScript Programming Language , Standard ECMA-262 3rd Edition - December 1999 is a subset. JSON is completely independent of the language used in text format, these properties make JSON an ideal data-interchange language.
Here are three of the java process json library: json-lib, gson, jackson
Json-lib
JSON-lib is a java library for transforming beans, maps, collections, java arrays and XML to JSON and back again to beans and DynaBeans. official website: http://json-lib.sourceforge.net/
maven dependency:
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
Example:
/**
* 将对象序列化成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
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.
official website: https://code.google.com/p/google-gson/
maven dependency:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.4</version>
</dependency>
Example:
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
Jackson is a high-performance JSON processor (parser, generator). Official website: http://jackson.codehaus.org/Home
maven dependency:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
Example:
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);
}
performance test
1, Java objects serialized as Json string:
perform one million conversions, time-consuming each library as follows: (in seconds)
Gson | 48.891s |
Json-lib | 311.446s |
Jackson | 19.439s |
2, Json string deserialize Java objects
perform one million conversions, time-consuming each library as follows: (in seconds)
Gson | 39.280s |
Json-lib | to use the library when converting method (test code see below), an exception is thrown. The reason is that the properties of the Person class: List |
Jackson | 26.427s |
3, Summary:
For Json serialization and deserialization performance Jackson> Gson> Json-lib. And Jackson and Gson can well support complex nested structure defined classes.
Jackson and Gson library has its own advantages, each with their own expertise, have a high availability.
4, test cases
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 library:
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);
}
}
3) Java objects serialized as Json string test class:
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(JsonObjectUtil.bean2Json(p));
for (int i = 0; i < 1000000; i++) {
JsonObjectUtil.bean2Json(p);
}
}
@Test
public void testJacksonBean2Json() throws Exception{
System.out.println(JacksonUtil.bean2Json(p));
for (int i = 0; i < 1000000; i++) {
JacksonUtil.bean2Json(p);
}
}
}
4) Json string deserialize Java objects test class:
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 testJsonObjectjson2Bean() throws Exception{
Person pp=JsonObjectUtil.json2Bean(jsonStr, Person.class);
System.out.println(pp);
for (int i = 0; i < 1000000; i++) {
JsonObjectUtil.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);
}
}
}
Reference: http://www.json.org/json-zh.html
没有评论:
发表评论