Java Json 序列化與反序列化
JSON</strong>(JavaScript Object Notation) 是一種輕量級的數據交換格式。 易于人閱讀和編寫。同時也易于機器解析和生成。 它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition
December 1999的一個子集。 JSON采用完全獨立于語言的文本格式,這些特性使JSON成為理想的數據交換語言。</span>
下面介紹兩款自己在開發中常用的處理Json的Java開源類庫:Gson和Fastjson
1、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.
Gson官網:http://code.google.com/p/google-gson/
Gson User Guide:https://sites.google.com/site/gson/gson-user-guide
2、Fastjson
Fastjson是一個json處理工具包,由阿里巴巴公司開發,包括“序列化”和“反序列化”兩部分,它具備如下特征:
- 速度最快,測試表明,fastjson具有極快的性能,超越任其他的java json parser。包括自稱最快的jackson。
- 功能強大,完全支持java bean、集合、Map、日期、Enum,支持范型,支持自省。
- 無依賴,能夠直接運行在Java SE 5.0以上版本
- 支持Android。
- 開源 (Apache 2.0)
下面通過一個簡單Demo,對比兩者 序列化與反序列化的用法
JavaBean 實體Person
package com.example.testjson.entity;
import java.util.Date;
import java.util.List;
import java.util.Map;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; public String getName() { return name; } public void setName(String name) { this.name = name; } public FullName getFullName() { return fullName; } public void setFullName(FullName fullName) { this.fullName = fullName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public List<String> getHobbies() { return hobbies; } public void setHobbies(List<String> hobbies) { this.hobbies = hobbies; } public Map<String, String> getClothes() { return clothes; } public void setClothes(Map<String, String> clothes) { this.clothes = clothes; } public List<Person> getFriends() { return friends; } public void setFriends(List<Person> friends) { this.friends = friends; } @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; public FullName(){ } public FullName(String firstName, String middleName, String lastName) { super(); this.firstName = firstName; this.middleName = middleName; this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getMiddleName() { return middleName; } public void setMiddleName(String middleName) { this.middleName = middleName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public String toString() { return "[firstName=" + firstName + ", middleName=" + middleName + ", lastName=" + lastName + "]"; }
} </pre></div> </div> </div>
</div>負責創建Person的Bean Factorypackage com.example.testjson.entity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;public class PersonFactory {
private static Person createABSPerson(String name,List<Person> friends) { Person newPerson = new Person(); newPerson.setName(name); newPerson.setFullName(new FullName(name+"_first", name+"_middle", name+"_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 Person create(String name){ List<Person> friends=new ArrayList<Person>(); friends.add(createABSPerson("小明",null)); friends.add(createABSPerson("Tony",null)); friends.add(createABSPerson("陳小二",null)); return createABSPerson(name,friends); }
} </pre></div> </div> </div>
</div>Gson 工具類GsonUtil
</div> </div>package com.example.testjson.gson;
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; }
} </pre>
</div>
Fastjson 工具類FastJsonUtil
</div> </div>package com.example.testjson.fastjson;
import com.alibaba.fastjson.JSON;
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); }
} </pre>
</div>最后兩個測試類
GsonTest
package com.example.testjson;
import com.example.testjson.entity.Person;
import com.example.testjson.entity.PersonFactory;
import com.example.testjson.gson.GsonUtil;public class GsonTest {
/** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Person p = PersonFactory.create("Kobe"); String json = GsonUtil.bean2Json(p); String prettyJsonString = GsonUtil.jsonFormatter(json); System.out.println("FastJson Serializing="+json); System.out.println("FastJson Serializing PrettyPrinting="+prettyJsonString); Person newPerson = GsonUtil.json2Bean(json, Person.class); System.out.println("FastJson Deserializing="+newPerson); }
} </pre></div> </div> </div>
</div>FastJsonTest
package com.example.testjson;
import com.example.testjson.entity.Person;
import com.example.testjson.entity.PersonFactory;
import com.example.testjson.fastjson.FastJsonUtil;public class FastJsonTest {
/** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Person p = PersonFactory.create("Kobe"); String json = FastJsonUtil.bean2Json(p); System.out.println("FastJson Serializing="+json); Person newPerson = FastJsonUtil.json2Bean(json, Person.class); System.out.println("FastJson Deserializing="+newPerson); }
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!相關經驗
相關資訊
相關文檔
目錄
sesese色