高性能JSON框架之FastJson的简单使用
fastjson阿里的json开源框架
特点
速度快,序列化反序列化都fast
功能强大(支持jdk类包括任意javabean class ,collection,map,date)
零依赖(没有依赖其他任何类库)
一个{}内的为一个json对象
json对象:JSONObject,JSONArray
json对象可直接转javabean
javabean可以直接转json对象(toJson())/也可线转化成json字符串(toJSONString()),再由字符串转json对象(parseObject())
json对象和字符串转javabean方法有2:
1.//第二种方式,使用TypeReference类,由于其构造方法使用protected进行修饰,故创建其子类
//Student student = JSONObject.parseObject(JSON_OBJ_STR, new TypeReference() {}); //第一个参数是json格式字符串
//第三种方式,使用Gson的思想
Student student = JSONObject.parseObject(JSON_OBJ_STR, Student.class);
FastJson对于json格式字符串的解析主要用到了下面三个类:
1.JSON:fastJson的解析器,用于JSON格式字符串(即String str="{“studentName”:“lily”,“studentAge”:12}")与JSON对象及javaBean之间的转换
2.JSONObject:fastJson提供的json对象
3.JSONArray:fastJson提供json数组对象
JSON格式字符串与JSON对象之间的转换
json字符串(简单对象型)
//jsonstring转json
jsonObject = JSONObject.parseObject(String);
jsonObject.getString(“key名称”);
jsonObject.getInteger("mingcheng ");
//json转字符串
1.JSONObject.toJSONString(jsonObject);
2.jsonObject.toJSONString();
json字符串(数组类型)与JSONArray之间的转换
json字符串(数组类型)
JSONArray.parseArray(JSON_ARRAY_STR);
遍历时
1.普通for循环
JSONObject jsonObject = jsonArray.getJSONObject(i);//获取jsonArray中的第i个json串
jsonObject .getString(‘ming’);
2. 增强for循环(foreach)
(JSONObject)obj;
jsonObject .getString(‘ming’);
//jsonArray转String
String jsonString = JSONArray.toJSONString(jsonArray);
复杂格式json字符串(包括一般类型和数组类型)
jsonObject = JSONObject.parseObject(String);
jsonObject .getJSONObject(“key名称”);
jsonObject.getJSONArray(“key名称”);
转String
jsonObject.toJSONString();
json格式字符串和javabean转换
//第一种方式
JSONObject jsonObject = JSONObject.parseObject(JSON_OBJ_STR);
String studentName = jsonObject.getString("studentName");
Integer studentAge = jsonObject.getInteger("studentAge");
//Student student = new Student(studentName, studentAge);
//第二种方式,使用TypeReference<T>类,由于其构造方法使用protected进行修饰,故创建其子类
//Student student = JSONObject.parseObject(JSON_OBJ_STR, new TypeReference<Student>() {});
//第三种方式,使用Gson的思想
Student student = JSONObject.parseObject(JSON_OBJ_STR, Student.class);
javabean转json串
JSONObject.toJSONString(javabean);
转javabean
//第二种方式,使用TypeReference类,由于其构造方法使用protected进行修饰,故创建其子类
List studentList = JSONArray.parseObject(JSON_ARRAY_STR, new TypeReference<ArrayList>() {});
System.out.println("studentList: " + studentList);
//第三种方式,使用Gson的思想
List<Student> studentList1 = JSONArray.parseArray(JSON_ARRAY_STR, Student.class);
System.out.println("studentList1: " + studentList1);
String jsonString = JSONArray.toJSONString(students);