Fastjson包使用總結

FastJSON是一個Java語言編寫的高性能,功能完善,完全支持http://json.org的標準的JSON庫。

MAVEN依賴

<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.23</version> </dependency>

 

---1.序列化---將JavaBean對象轉成JSON格式的字符創

---2.反序列化--將JSON格式的字符串轉化成JAVA Bean 對象

 

---1--1--基本的序列化--JSON.toJSONString

Map<String,Object> map = new HashMap<String,Object>();

map.put("姓名","張三");

map.put("年齡","18");

map.put("性別","男");

System.out.println(map);

//基本序列化將Map轉換成JSON

String mapJson = JSON.toJSONString(map);

System.out.printf(mapJson);

 

---1--2--將List<Map> 轉成JSON

 

List<Map<String,Object>> list = new ArrayList<Map<String, Object>>();

Map<String, Object> map1 = new HashMap<String,Object>();

map1.put("姓名","張三");

map1.put("性別","男");

map1.put("年齡","18");

 

Map<String, Object> map2 = new HashMap<String,Object>();

map2.put("姓名","李四");

map2.put("性別","女");

map2.put("年齡","16");

 

list.add(map1);

list.add(map2);

 

String listJson = JSON.toJSONString(list);

System.out.printf(listJson);

 

---1--3--將自定義JavaBean對象轉化成JSON格式

 

User user = new User();

user.setUserName("張三");

user.setAge(18);

 

System.out.println(user);

String userString = JSON.toJSONString(user);

System.out.println(userString);

 

---1--4--幾個FastJson的常用特性

1.日期格式化,FastJson可以直接對日期進行格式化,在缺省的情況下,FastJson會將Data轉成Long

Date date = new Date();

String dataString = JSON.toJSONString(date);

System.out.println(date);

System.out.println(dataString);

 

2.使用SerializerFeature特性格式化日期

Date date = new Date();

String dateJson = JSON.toJSONString(date, SerializerFeature.WriteDateUseDateFormat);

System.out.println(dateJson);

3.指定輸出日期格式

Date date = new Date();

String dateJson = JSON.toJSONStringWithDateFormat(date,"yyyy-MM-dd HH:mm:ss.SSS");

System.out.println(dateJson);

 

---2--1--FastJson的 反序列化--JSON.parseObject(userJson,User.class)

 

User user = new User();

user.setUserName("李四");

user.setAge(24);

 

String userJson = JSON.toJSONString(user);

System.out.println(userJson);

///////////////////////////////////////////////////////疑惑

User userJ = JSON.parseObject(userJson,User.class);

System.out.println(userJ);

System.out.println(userJ.getUserName());

System.out.println(userJ.getAge());

System.out.println(userJ.getClass());

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章