fastjson与net.sf.json都是开源java类库,都可以解析JSON格式的字符串,支持将Java Bean序列化为JSON字符串,也可以从JSON字符串反序列化到JavaBean。其中的fastjson是阿里巴巴的开源JSON解析库,相对net.sf.json有更快的性能优势,同时可以避免使用net.sf.json过程中的一些莫名其妙的问题。所以在一般的项目中,绝大多数引用阿里巴巴的fastjson。
1、fastjson
Fastjson 是一个java类库,可以被用来把Java对象转换成Json方式,也可以把Json字符串转换成对应的Java对象,Fastjson可以作用于任何Java对象,包含没有源代码已存在的对象。
- fastjson优点:速度快、使用广泛、使用简单、功能完备、测试完备,现在使用fastjson至少升级到1.2.60版本
- fastjson是目前java语言中最快的json库,比自称最快的jackson速度要快。速度快的原因:
- 1、自行编写类似StringBuilder的工具类SerializeWriter。
- 2、使用ThreadLocal来缓存buf。
- 3、使用asm避免反射
- 4、集成jdk实现的一些优化算法
1.1 引入com.alibaba.fastjson包
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.66</version>
</dependency>
fastjson的使用主要是三个对象:JSON、JSONObject、JSONArray
1.2 常用转换方法
1)Java对象与JSON对象互转
Student stu = new Student("孔子说java", "m", 2);
// Java对象转化为JSON对象
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(stu);
System.out.println("Java对象转化为JSON对象:" + jsonObject);
// Java对象转化为JSON对象:{"name":"语文","age":2,"sex":"m"}
// JSON对象转化为Java对象
Student student = JSONObject.toJavaObject(jsonObject, Student.class);
System.out.println("JSON对象转换成Java对象:" + student);
// JSON对象转换成Java对象:{name='孔子说java', sex='m', age=2}
2)Java对象与JSON字符串互转
Student stu = new Student("孔子说java", "m", 2);
//Java对象转换成JSON字符串
String stuString = JSONObject.toJSONString(stu);
System.out.println("Java对象转换成JSON字符串:" + stuString);
// Java对象转换成JSON字符串:{"age":2,"name":"孔子说java","sex":"m"}
// String stuString = "{\"age\":2,\"name\":\"孔子说java\",\"sex\":\"m\"}";
//JSON字符串转换成Java对象
Student student1 = JSONObject.parseObject(stuString, Student.class);
System.out.println("JSON字符串转换成Java对象:" + student1);
// JSON字符串转换成Java对象:Student{name='孔子说java', sex='m', age=2}
3)JSON对象与JSON字符串互转
Student stu = new Student("孔子说java", "m", 2);
//先转成JSON对象
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(stu);
//JSON对象转换为JSON字符串
String jsonString = jsonObject.toJSONString();
System.out.println("JSON对象转换为JSON字符串:" + jsonString);
// JSON对象转换为JSON字符串:{"name":"孔子说java","age":2,"sex":"m"}
// String stuString = "{\"age\":2,\"name\":\"孔子说java\",\"sex\":\"m\"}";
//JSON字符串转换成JSON对象
JSONObject jsonObject1 = JSONObject.parseObject(stuString);
System.out.println("孔子说java:" + jsonObject1);
// JSON字符串转换成JSON对象:{"sex":"m","name":"孔子说java","age":2}
4)List对象与JSON字符串互转
// List转json字符串
List list = new ArrayList();
list.add(new Student("lwc", "111111"));
list.add(new Student("nxj", "222222"));
//将list集合转为json数组对象
JSONArray array= JSONArray.parseArray(JSON.toJSONString(list));
// JSONArray转List
JSONArray array = new JSONArray();
List<Student> list = JSONObject.parseArray(array.toJSONString(), Student.class);
// json字符串转List
String jsondata = "[{"password":"111111","username":"lwc"},{"password":"222222","username":"nxj"}]";
List<Student> list = JSONObject.parseArray(jsondata, Student.class);
// list集合转换为json字符串
JSON.stringify(list);
5)Map对象与JSON字符串互转
Map obj= JSONObject.parseObject(jsonString, Map.class);
JSONObject jo = JSON.parseObject(jsonSt);//JSONObject本身就是map
JSONArray ja = JSON.parseArray(jsonListSt);//JSONArray本身就是list
String s ="{\"action\":\"add\",\"id\":\"1\",\"ordinal\":8,\"organUnitFullName\":\"testJSON\",\"parent\":\"0\",\"suborderNo\":\"58961\"}";
JSONObject jsonObject = JSON.parseObject(s);
String action = jsonObject.getString("action");
String id = jsonObject.getString("id");
System.out.println("action ="+action);//add
System.out.println("id ="+id);//1
System.out.println("jsonObject ="+jsonObject);
6)JSONArray与List互转
// list转jsonArray
JSONArray array = JSONArray.parseArray(JSONObject.toJSONString(mans));
// jsonArray转list
List<Man> list = JSONObject.parseArray(js2.toJSONString(), Man.class);
7)其他例子
// Object转json
JSONObject j1 = (JSONObject)JSONObject.toJSON(man1);
// json转Object
Man man3 = JSONObject.parseObject(j2.toJSONString(), Man.class);
String aaa = "{\"name\":\"张三\",\"id\":\"1\"}";
// String转JSONObject
JSONObject j1 = JSONObject.parseObject(aaa);
// JSONObject转String
String bbb = j1.toJSONString();
String aaa = "[{\"name\":\"张三\",\"id\":\"1\"},{\"name\":\"李四\",\"id\":\"2\"}]";
// String转jsonArray
JSONArray jsArr = JSONObject.parseArray(aaa);
// jsonArray转String
String bbb = jsArr.toJSONString();
2、net.sf.json
2.1 引入net.sf.json包
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
2.2 常用转换方法
1)Java对象与JSON对象互转示例
Student stu = new Student("孔子说java", "m", 2);
// Java对象转为json对象(不论是json字符串还是java对象都是这个方法)
JSONObject jsonObject = JSONObject.fromObject(stu);
System.out.println(jsonObject);
// json对象转为Java对象
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "孔子说java");
jsonObject.put("age", "2");
jsonObject.put("sex", "m");
Student user = (Student)JSONObject.toBean(jsonObject, Student.class);
System.out.println(user.toString());
2)Java对象与JSON字符串互转
Student stu = new Student("孔子说java", "m", 2);
// Java对象转为json对象(不论是json字符串还是java对象都是这个方法)
JSONObject jsonObject = JSONObject.fromObject(stu);
// json对象转为JSON字符串
String jsonStr = jsonObject.toString();
System.out.println(jsonStr);
// json字符串转JavaBean
String stuString = "{\"age\":2,\"name\":\"孔子说java\",\"sex\":\"m\"}";
JSONObject jsonObject = JSONObject.fromObject(stuString);
Student stu2 = (Student) JSONObject.toBean(jsonObject, Student.class);
System.out.println(stu2);
3)JSON对象与JSON字符串互转
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "孔子说java");
jsonObject.put("age", "2");
jsonObject.put("sex", "m");
// Java对象转为json字符串
String jsonStr = jsonObject.toString();
System.out.println(jsonStr);
// JSON字符串转JSON对象
String stuString = "{\"age\":2,\"name\":\"孔子说java\",\"sex\":\"m\"}";
JSONObject jsonObject = JSONObject.fromObject(stuString);
System.out.println(jsonObject.toString());
4)List对象与JSON字符串互转
// List转json字符串
List list = new ArrayList();
list.add(new Student("lwc", "111111"));
list.add(new Student("nxj", "222222"));
//将list集合转为json数组对象
JSONArray jsonArray = JSONArray.fromObject(list);
System.out.println(jsonArray);
// json字符串转List
List list1 = new ArrayList();
String jsondata = "[{"password":"111111","username":"lwc"},{"password":"222222","username":"nxj"}]";
JSONArray jsonArray1 = JSONArray.fromObject(jsondata);
for (int i = 0; i < jsonArray1.size(); i++) {
JSONObject jsonObject2 = jsonArray1.getJSONObject(i);
Student stu2 = (Student) JSONObject.toBean(jsonObject2, Student.class);
list1.add(stu2);
}
System.out.println(list1);
5)Map对象与JSON字符串互转
// Map转json字符串
Map map = new HashMap();
map.put("1", new Student("lwc", "111111"));
map.put("2", new Student("nxj", "222222"));
JSONObject jsonMap = JSONObject.fromObject(map);
System.out.println(jsonMap);
// json字符串转Map
String jsondata = "{"2":{"password":"222222","username":"nxj"},"1":{"password":"111111","username":"lwc"}}";
Map map1 = (Map) JSONObject.fromObject(jsondata);
Set set = map1.keySet();
Iterator ite = set.iterator();
while (ite.hasNext()) {
String key = (String) ite.next();
JSONObject jsonObject = JSONObject.fromObject(map1.get(key));
Student stu = (Student) JSONObject.toBean(jsonObject, Student.class);
System.out.println(key + " " + stu);
}
6)JSONArray与List互转
//List转型JSONArray
List<Student> list = new ArrayList<Student>();
list.add(new Student("lwc", "111111"));
list.add(new Student("nxj", "222222"));
JSONArray jsonArray = JSONArray.fromObject(list);
System.out.println(jsonArray.toString());
//JSONArray转型List
List<Student> list2 = JSONArray.toList(jsonArray, new Student(), new JsonConfig());
Iterator<Student> ite = list2.iterator();
while(ite.hasNext()){
Student stu =ite.next();
System.out.println(stu);
}
7)JSONArray与数组互转
// Java数组转JSONArray
boolean[] boolArray = new boolean[] { true, false, true };
JSONArray jsonArray = JSONArray.fromObject(boolArray);
System.out.println(jsonArray.toString());
// JSONArray转Java数组
Object obj[] = jsonArray.toArray();
for (Object o : obj) {
System.out.print(o + " ");
}
8)其他例子
// string字符串转json数组
String json = “[{‘day1’:’work’,’day2’:26},{‘day1’:123,’day2’:26}]”;
JSONArray jsonArray = JSONArray.fromObject(json);
// 获取每个成员的key及value
JSONObject obj = (JSONObject) jsonArray.get(i);
Iterator it = obj.keys();
while (it.hasNext()) {
String key = it.next().toString();
System.out.println("key ----- "+key);
System.out.println("value ----- "+obj.get(key));
}
// 增加
JSONObject obj2 = new JSONObject();
obj2.put("day1", "study");
obj2.put("day2", "2");
jsonArray.add(obj2);
// 删除
jsonArray.remove(index);
jsonArray.subList(fromIndex, toIndex)
3、net.sf.json使用问题
3.1 解析json精度丢失
json数据如下:
{“vector”:[0.0,151.42662048339844,31.855236053466797,4.355315208435059,35.25135803222656,4.608330726623535],“success”:true}
vector的值是double数组类型,使用net.sf.json.JSONObject方法获取vector的数据:
JSONObject objData = new JSONObject().fromObject(jsonString);
Boolean suc = (Boolean)objData.get("success");
String vecStr = objData.get("feature_vector").toString();
得到的vecStr值为:0,151.42662,31.855236,4.355315,35.251358,4.6083307。精度由15位被截取到6~7位。
解决方案
使用com.alibaba.fastjson.JSONObject,如下:
Map obj= JSONObject.parseObject(jsonString, Map.class);
Boolean suc = (Boolean)obj.get("success");
String vecStr =obj.get("feature_vector").toString();
得到的vecStr的值为:[0.0,151.42662048339844,31.855236053466797,4.355315208435059,35.25135803222656,4.608330726623535]
3.2 无法区分 “null” 和 null
在Java程序中 “null” 和 null 有天大的区别。有个json如下:
{"create_dtime":null}
1)使用 net.sf.json 解析如下:
String jsonStr = "{\"create_dtime\":null}";
JSONObject jo = JSONObject.from(jsonStr);
System.out.println(jo.get("create_dtime")==null);
当我以为他会输出true的时候,他却输出的是false,因为 net.sf.json 将 null 转为了字符串。
2)使用 fastjson 解析如下:
String jsonStr = "{\"create_dtime\":null}";
JSONObject jo = JSONObject.parseObject(jsonStr);
System.out.println(jo.get("create_dtime")==null);
输出结果是我们期望的true。
3.3 解析效率低
使用net.sf.json.JSONArray.fromObject解析json字符串效率很低,如:有几百个json文件,每个文件70M左右,json文件的格式为:[{“str”: “xxx”, “num”: “2055”}, {“str”: “aaa”,“num”:“2542”},…]
,使用 JSONArray.fromObject 方法解析如下:
Long start = System.currentTimeMillis();
JSONArray arrData = JSONArray.fromObject(json);
List<Map<String, String>> maps = JSONArray.toList(arrData, Map.class);
Long end = System.currentTimeMillis();
System.out.println(end-start);
- 执行以上程序解析json文件花费时间约126820ms。
使用 com.alibaba.fastjson,代码如下:
Long start = System.currentTimeMillis();
List<Map> maps = JSONObject.parseArray(json, Map.class);
Long end = System.currentTimeMillis();
System.out.println(end-start);
- 使用alibaba.fastjson执行程序解析json文件花费311ms,可以看到效率天壤之别!
4、拓展:XML与JSON互转
前提:需要导入xom-1.1.jar
package com.itlwc.test;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;
public class Test {
public static void main(String[] args) throws Exception {
// XML转JSON
String xml = "<root>" + "<name type='type'>zhaipuhong</name>"
+ "<gender>male</gender>" + "<birthday>" + "<year>1970</year>"
+ "<month>12</month>" + "<day>17</day>" + "</birthday>"
+ "</root>";
XMLSerializer xmlSerializer = new XMLSerializer();
JSON json = xmlSerializer.read(xml);
System.out.println(json.toString(2));
// JSON转XML
String jsondata = "{"root":{" + ""name":"zhaipuhong","
+ ""gender":"male"," + ""birthday":{"
+ ""year":"1970"," + ""month":"12"," + ""day":"17""
+ "}" + "}" + "}";
JSONObject jsonObject = JSONObject.fromObject(jsondata);
String xmlstr = new XMLSerializer().write(jsonObject);
System.out.println(xmlstr);
}
}
/*
打印结果:
{
"name": "zhaipuhong",
"gender": "male",
"birthday": {
"year": "1970",
"month": "12",
"day": "17"
}
}
<?xml version="1.0" encoding="UTF-8"?>
<o>
<root class="object">
<birthday class="object">
<day type="string">17</day>
<month type="string">12</month>
<year type="string">1970</year>
</birthday>
<gender type="string">male</gender>
<name type="string">zhaipuhong</name>
</root>
</o>
*/
评论区