fastjson 是一个性能很好的 Java 语言实现的 JSON 解析器和生成器,来自阿里巴巴的工程师开发。
主要特点:
-
快速FAST (比其它任何基于Java的解析器和生成器更快,包括jackson)
-
强大(支持普通JDK类包括任意Java Bean Class、Collection、Map、Date或enum)
-
零依赖(没有依赖其它任何类库除了JDK)
FastJSON是一个Java语言编写的高性能,功能完善,完全支持http://json.org的标准的JSON库
在使用之前必须下载这个包:fastjson-1.1.37.jar 或fastjson-1.1.39.jar (注意JDK的版本哦!)
一.序列化就是把JavaBean对象转成JSON格式的字符串![](https://img-blog.csdn.net/20161112113603033?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
/**
* 实体类
*
* @author Administrator
*
*/
public class Student {
private String name; // 用户名
private int age; // 年龄
............
}
具体的使用如下:
/**
* (1)将实体对象转换成JSON对象
* String str_json = JSON.toJSONString(stu);
*/
public static void entityToJSON() {
// 对象
Student stu = new Student("zhangsan", 20);
// 将对象转换成JSON对象
String str_json = JSON.toJSONString(stu);
// 输出
System.out.println("实体转化为Json" + str_json);
}
/**
* (2)将List对象转换成JSON对象
String json = JSON.toJSONString(list, true);
*/
public static void listToJSON() {
List<Student> list = new ArrayList<Student>();
Student userinfo1 = new Student("mike", 25);
Student userinfo2 = new Student("boy", 26);
list.add(userinfo1);
list.add(userinfo2);
// true:是格式化样式
String json = JSON.toJSONString(list, true);
System.out.println("List集合转json格式字符串 :" + json);
}
/**
* (4)将复杂数据类型转换成JSON对象
* String jsonString = JSON.toJSONString(map,true);
*
*/
public static void MoreToJSON() {
// map集合
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("uname", "小飞");
map.put("age", 21);
map.put("sex", "F");
// map集合
HashMap<String, Object> temp = new HashMap<String, Object>();
temp.put("name", "小明");
temp.put("age", "23");
// 将temp添加map集合中
map.put("girlInfo", temp);
// list集合
List<String> list = new ArrayList<String>();
list.add("aaa");
list.add("bbb");
list.add("ccc");
// 将list添加map集合中
map.put("hobby", list);
String jsonString = JSON.toJSONString(map,true);
System.out.println("复杂数据类型:" + jsonString);
}
/**
* (6)通过JSON将日期格式化
*
*/
public static void formatDate() {
//日期
Date date= new Date();
String str = JSON.toJSONString(date);
System.out.println("输出毫秒:"+str);
String dstr=JSON.toJSONString(date, SerializerFeature.WriteDateUseDateFormat);
System.out.println("输出默认格式:"+dstr);
String zstr=JSON.toJSONStringWithDateFormat(date,"yyyy-MM-dd", SerializerFeature.WriteDateUseDateFormat);
System.out.println("自定义格式:"+zstr);
}
二.反序列化就是把JSON格式的字符串转化为Java Bean对象。
/**
* (3)将字符数组转换成JSON对象
* JSONArray array = JSONArray.parseArray(string);
*/
public static void StringArrayToJSON() {
String string = "[['熊二',20],null,['翠花',21]]";
JSONArray array = JSONArray.parseArray(string);
System.out.println("数组:" + array);
System.out.println("数组长度: " + array.size());
}
/**
* (5)将JSON对象转换成实体对象
* Student stu = JSON.parseObject(json, Student.class);
*/
public static void JsonToEntity() {
//json
String json="{'name':'girl',age:20}";
// 将JSON转换成实体对象
Student stu = JSON.parseObject(json, Student.class);
// 输出
System.out.println("Json转化为实体:" + stu);
}