一、FastJson简介
fastjson是用于java后台处理json格式数据的一个工具包,包括“序列化”和“反序列化”两部分,它具备如下特征:
- 速度最快,测试表明,fastjson具有极快的性能,超越任其他的java json parser。
- 功能强大,完全支持java bean、集合、Map、日期、Enum,支持范型,支持自省。
- 无依赖,能够直接运行在Java SE 5.0以上版本
fastjson的作用就是把 java 对象转化为字符串
,把字符串转化为java对象
,然后方便进行后续的逻辑处理。
二、FastJson主要类
fastjson对于json格式字符串的解析主要用到了一下三个类
JSON
用于JSON格式字符串与JSON对象及javaBean之间的转换
package com.alibaba.fastjson;
/**
* This is the main class for using Fastjson. You usually call these two methods {@link #toJSONString(Object)} and {@link #parseObject(String, Class)}.
*
* <p>Here is an example of how fastjson is used for a simple Class:
*
* <pre>
* Model model = new Model();
* String json = JSON.toJSONString(model); // serializes model to Json
* Model model2 = JSON.parseObject(json, Model.class); // deserializes json into model2
* </pre>
*
* <p>If the object that your are serializing/deserializing is a {@code ParameterizedType}
* (i.e. contains at least one type parameter and may be an array) then you must use the
* {@link #toJSONString(Object)} or {@link #parseObject(String, Type, Feature[])} method. Here is an
* example for serializing and deserialing a {@code ParameterizedType}:
*
* <pre>
* String json = "[{},...]";
* Type listType = new TypeReference<List<Model>>() {}.getType();
* List<Model> modelList = JSON.parseObject(json, listType);
* </pre>
*
* @see com.alibaba.fastjson.TypeReference
*
* @author wenshao[szujobs@hotmail.com]
*/
public abstract class JSON implements JSONStreamAware, JSONAware{
//需要重点关注的方法
parse
parseObject
parseArray
toJSONString
toJSONBytes
writeJSONString
toJavaObject
}
JSONObject
JSONObject //需要重点关注的方法
parseObject
getJSONArray
getJSONObject
getObject
containsKey
JSONArray
三、准备工作
实体类:Resp
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Resp implements Serializable {
private static final long serialversionuid = -6957361951748382519L;
private String id;
private String suborderNo;
private String organUnitType;
private String action;
private String parent;
private String organUnitFullName;
private Long ordinal;
}
实体类:MyERROR
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MyERROR implements Serializable {
private String code;
private String message;
private String success;
private List<Resp> data = new ArrayList<>();
}
json字符串:
{
"meta": {
"code": "0",
"message": "同步成功!"
},
"data": {
"orderno": "U_2018062790915774",
"suborderno": "SUB_2018062797348039",
"type": "organunit",
"result": {
"organunit": {
"totalCount": 2,
"successCount": 0,
"failCount": 2,
"errors": [
{
"code": "UUM70004",
"message": "组织单元名称不能为空",
"data": {
"id": "254",
"suborderNo": "SUB_2018062797348039",
"organUnitType": "部门",
"action": "add",
"parent": "10000",
"ordinal": 0,
"organUnitFullName": "组织单元全称"
},
"success": false
},
{
"code": "UUM70004",
"message": "组织单元名称不能为空",
"data": {
"id": "255",
"suborderNo": "SUB_2018062797348039",
"organUnitType": "部门",
"action": "add",
"parent": "10000",
"ordinal": 0,
"organUnitFullName": "组织单元全称"
},
"success": false
}
]
},
"role": {
"totalCount": 0,
"successCount": 0,
"failCount": 0,
"errors": []
},
"user": {
"totalCount": 0,
"successCount": 0,
"failCount": 0,
"errors": []
}
}
}
}
看一下格式化之后的json数据:
四、示例
4.1 java对象转JSON字符串
//java对象转json字符串
public static void beanTojson() {
Resp resp = new Resp();
resp.setAction("add");
resp.setId("1");
resp.setOrdinal(8L);
resp.setOrganUnitFullName("testJSON");
resp.setParent("0");
resp.setSuborderNo("58961");
String s = JSON.toJSONString(resp);
System.out.println("toJsonString()方法:s=" + s);
//输出结果{"action":"add","id":"1","ordinal":8,"organUnitFullName":"testJSON","parent":"0","suborderNo":"58961"}
}
4.2 JSON字符串转JSON对象
//json字符串转json对象
public static void jsonToJsonBean() {
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);
//jsonObject ={"parent":"0","organUnitFullName":"testJSON","action":"add","id":"1","suborderNo":"58961","ordinal":8}
}
4.3 复杂JSON格式字符串与JSONObject之间的转换
public static void jsonToBean() {
String str ="{\"meta\":{\"code\":\"0\",\"message\":\"同步成功!\"},\"data\":{\"orderno\":\"U_2018062790915774\",\"suborderno\":\"SUB_2018062797348039\",\"type\":\"organunit\",\"result\":{\"organunit\":{\"totalCount\":2,\"successCount\":0,\"failCount\":2,\"errors\":[{\"code\":\"UUM70004\",\"message\":\"组织单元名称不能为空\",\"data\":{\"id\":\"254\",\"suborderNo\":\"SUB_2018062797348039\",\"organUnitType\":\"部门\",\"action\":\"add\",\"parent\":\"10000\",\"ordinal\":0,\"organUnitFullName\":\"组织单元全称\"},\"success\":false},{\"code\":\"UUM70004\",\"message\":\"组织单元名称不能为空\",\"data\":{\"id\":\"255\",\"suborderNo\":\"SUB_2018062797348039\",\"organUnitType\":\"部门\",\"action\":\"add\",\"parent\":\"10000\",\"ordinal\":0,\"organUnitFullName\":\"组织单元全称\"},\"success\":false}]},\"role\":{\"totalCount\":0,\"successCount\":0,\"failCount\":0,\"errors\":[]},\"user\":{\"totalCount\":0,\"successCount\":0,\"failCount\":0,\"errors\":[]}}}}";
JSONObject jsonObject = JSON.parseObject(str);
JSONObject data = jsonObject.getJSONObject("data");
JSONObject result = data.getJSONObject("result");
String organunit1 = result.getString("organunit");
System.out.println(organunit1);
JSONObject organunit = result.getJSONObject("organunit");
JSONArray errors2 = organunit.getJSONArray("errors");
List<MyERROR> errors = JSON.parseObject(errors2.toJSONString(), new TypeReference<List<MyERROR>>() {});
for (MyERROR error : errors) {
System.out.println(error);
}
System.out.println("==========================>");
//JSONObject 可以链式调用
JSONArray jsonArray = JSON.parseObject(str).getJSONObject("data").getJSONObject("result").getJSONObject("organunit").getJSONArray("errors");
List<MyERROR> myERRORS = JSON.parseObject(jsonArray.toJSONString(), new TypeReference<List<MyERROR>>() {});
for (MyERROR error : myERRORS) {
System.out.println(error);
}
}
打印结果:
4.4 JSON字符串转Java简单对象
public static void jsonStrToJavaBean() {
String s ="{\"action\":\"add\",\"id\":\"1\",\"ordinal\":8,\"organUnitFullName\":\"testJSON\",\"parent\":\"0\",\"suborderNo\":\"58961\"}";
Resp data = JSON.parseObject(s, Resp.class);
System.out.println("data对象"+data.toString());
System.out.println("action="+data.getAction()+"---id="+data.getId()); //1
//另一种方式转对象
Resp dd = JSON.parseObject(s, new TypeReference<Resp>() {});
System.out.println("另一种方式获取data对象"+dd.toString());
System.out.println("另一种方式获取="+dd.getAction()+"---id="+dd.getId()); //1
}
4.5 JSON字符串 数组类型与Java对象的转换
public static void jsonStrToJSONArray() {
String str = "{\"errors\":[{\"code\":\"UUM70004\",\"message\":\"组织单元名称不能为空\",\"data\":{\"id\":\"254\",\"suborderNo\":\"SUB_2018062797348039\",\"organUnitType\":\"部门\",\"action\":\"add\",\"parent\":\"10000\",\"ordinal\":0,\"organUnitFullName\":\"组织单元全称\"},\"success\":false},{\"code\":\"UUM70004\",\"message\":\"组织单元名称不能为空\",\"data\":{\"id\":\"255\",\"suborderNo\":\"SUB_2018062797348039\",\"organUnitType\":\"部门\",\"action\":\"add\",\"parent\":\"10000\",\"ordinal\":0,\"organUnitFullName\":\"组织单元全称\"},\"success\":false}]}";
JSONArray error = JSON.parseObject(str).getJSONArray("errors");
List<MyERROR> errors = JSON.parseObject(error.toJSONString(),
new TypeReference<List<MyERROR>>() {});
for (MyERROR e: errors) {
//Error的属性
System.out.println("MyERROR.message属性="+e.getMessage());
System.out.println("MyERROR.code属性="+e.getCode());
System.out.println("MyERROR.success属性="+e.getSuccess());
List<Resp> datas = e.getData();
for (Resp d: datas) {
System.out.println("data对象属性="+d.getId());
System.out.println("data对象属性="+d.getAction());
System.out.println("data对象属性="+d.getSuborderNo());
}
System.out.println("------------------------------>");
}
}
4.6 Java对象转JSON对象
public static void beanToJsonObject() {
Resp data = new Resp();
data.setAction("add");
data.setId("1");
data.setOrdinal(8L);
data.setOrganUnitFullName("testJSON");
data.setParent("0");
data.setSuborderNo("58961");
JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(data));
JSONObject jsonObj = (JSONObject) JSON.toJSON(data);
JSON json = (JSON) JSON.toJSON(data);
System.out.println(jsonObj);
System.out.println(json);
System.out.println(jsonObject);
}