FastJson解析JSON数据
程序员文章站
2022-06-17 09:05:55
...
阿里巴巴FastJson是一个Json处理工具包,包括“序列化”和“反序列化”两部分,它具备如下特征:
速度最快,测试表明,fastjson具有极快的性能,超越任其他的Java Json parser。包括自称最快的JackJson;
功能强大,完全支持Java Bean、集合、Map、日期、Enum,支持范型,支持自省;无依赖,能够直接运行在Java SE 5.0以上版本;支持Android;开源 (Apache 2.0)
源码地址:https://github.com/alibaba/fastjson
Fastjson API入口类是com.alibaba.fastjson.JSON,常用的序列化操作都可以在JSON类上的静态方法直接完成。
public static final Object parse(String text); // 把JSON文本parse为JSONObject或者JSONArray
*public static final JSONObject parseObject(String text); // 把JSON文本parse成JSONObject
*public static final T parseObject(String text, Class clazz); // 把JSON文本parse为JavaBean
*public static final JSONArray parseArray(String text); // 把JSON文本parse成JSONArray
*public static final List parseArray(String text, Class clazz); //把JSON文本parse成JavaBean集合
*public static final String toJSONString(Object object); // 将JavaBean序列化为JSON文本
public static final String toJSONString(Object object, boolean prettyFormat); // 将JavaBean序列化为带格式的JSON文本
public static final Object toJSON(Object javaObject); 将JavaBean转换为JSONObject或者JSONArray。
不需要单独下载jar包,只需要修改pom.xml文件;
这串Json数据分为3层,最外层的”status”,”msg”和”data”; 然后”data”里面的”start”,”limit”,”total”,”rows”;最后”rows”里面的JSONArray。
Info_util.java:
除去必要的3个封装类,解析Json的就那么三行代码,如果Json数据结构简单甚至可能只需要一行代码。
速度最快,测试表明,fastjson具有极快的性能,超越任其他的Java Json parser。包括自称最快的JackJson;
功能强大,完全支持Java Bean、集合、Map、日期、Enum,支持范型,支持自省;无依赖,能够直接运行在Java SE 5.0以上版本;支持Android;开源 (Apache 2.0)
源码地址:https://github.com/alibaba/fastjson
Fastjson API入口类是com.alibaba.fastjson.JSON,常用的序列化操作都可以在JSON类上的静态方法直接完成。
public static final Object parse(String text); // 把JSON文本parse为JSONObject或者JSONArray
*public static final JSONObject parseObject(String text); // 把JSON文本parse成JSONObject
*public static final T parseObject(String text, Class clazz); // 把JSON文本parse为JavaBean
*public static final JSONArray parseArray(String text); // 把JSON文本parse成JSONArray
*public static final List parseArray(String text, Class clazz); //把JSON文本parse成JavaBean集合
*public static final String toJSONString(Object object); // 将JavaBean序列化为JSON文本
public static final String toJSONString(Object object, boolean prettyFormat); // 将JavaBean序列化为带格式的JSON文本
public static final Object toJSON(Object javaObject); 将JavaBean转换为JSONObject或者JSONArray。
以上加*的是一些项目中的常用方法。
-----------------------------------------------------------------------
为什么使用FastJson?
解析速度快、解析方便、使用简单。
首先,看一下解析的代码量
iu = Fast.parseObject(JsonString.JsonStringValues, Info_util.class);//取得第一层JSONObject
du = Fast.parseObject(iu.getData(), Info_data_util.class);//取得第二层JSONObject
olist = Fast.parseArray(du.getRows(), Info_array_Util.class);//取得第三层JSONArray
就两三行代码。再来看看以前常用的JsonObject以及JsonArray解析
JSONObject result= new JSONObject(jsonString);
JSONArray jsonArray = result .getJSONArray("List");
for (int i = 0; i < jsonArray.length; i++) {
JSONObject json=jsonArray.getJSONObject(i);
json.getString("...");
...
...
}
这种一个个去获取,很麻烦。
使用FastJson的方法如下:
需要下载FastJson的jar包,我是利用eclipse工具+Maven;不需要单独下载jar包,只需要修改pom.xml文件;
pom.xml文件如下:
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.46</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
有一串这样的Json数据:
{
"status": 1,
"msg": null,
"data": {
"start": 0,
"limit": 10,
"total": 5,
"rows": [
{
"messageNo": "Me201607211148242364423",
"memberNo": "AD2016070812145640900000003",
"mobileNo": "151****1314",
"nickname": "远方",
"headPath": "/fileupload/memberImage/83788978A0614007BF7F5D20F668088A1468667650848.jpg",
"messageType": 0,
"readFlag": 0,
"sendTime": 1469072904000,
"content": " ",
"updateTime": 1469072904000
},
{
"messageNo": "Me201607211146458551987",
"memberNo": "AD2016070812145640900000003",
"mobileNo": "151****1314",
"nickname": "远方",
"headPath": "/fileupload/memberImage/83788978A0614007BF7F5D20F668088A1468667650848.jpg",
"messageType": 0,
"readFlag": 0,
"sendTime": 1469072805000,
"content": "有6",
"updateTime": 1469072805000
},
{
"messageNo": "Me201607191730505629442",
"memberNo": "AD2016070810124275700000002",
"mobileNo": "156****3913",
"nickname": "呵呵",
"headPath": "/fileupload/memberImage/FD5DAE12CB79447BB5263EB0EE4E75F41469069984778.jpg",
"messageType": 0,
"readFlag": 0,
"sendTime": 1468920650000,
"content": "额",
"updateTime": 1468920650000
},
{
"messageNo": "Me201607161049255579387",
"memberNo": "AD2016070812145640900000003",
"mobileNo": "151****1314",
"nickname": "远方",
"headPath": "/fileupload/memberImage/83788978A0614007BF7F5D20F668088A1468667650848.jpg",
"messageType": 1,
"readFlag": 0,
"sendTime": 1468637365000,
"content": "111",
"updateTime": 1468637365000
},
{
"messageNo": "Me201607161037444613493",
"memberNo": "AD2016070812145640900000003",
"mobileNo": "151****1314",
"nickname": "远方",
"headPath": "/fileupload/memberImage/83788978A0614007BF7F5D20F668088A1468667650848.jpg",
"messageType": 0,
"readFlag": 0,
"sendTime": 1468636664000,
"content": "哈哈哈",
"updateTime": 1468636664000
}
],
"otherData": null
}
}
这串Json数据分为3层,最外层的”status”,”msg”和”data”; 然后”data”里面的”start”,”limit”,”total”,”rows”;最后”rows”里面的JSONArray。
源代码如下:
JsonString.java:
package com.accord.fastjson;
public class JsonString {
public static final String JsonStringValues = "{\"status\":1,\"msg\":null,"
+ "\"data\":{\"start\":0,\"limit\":10,\"total\":5,"
+ "\"rows\":[{\"messageNo\":\"Me201607211148242364423\","
+ "\"memberNo\":\"AD2016070812145640900000003\","
+ "\"mobileNo\":\"151****1314\","
+ "\"nickname\":\"远方\","
+ "\"headPath\":\"/fileupload/memberImage/83788978A0614007BF7F5D20F668088A1468667650848.jpg\","
+ "\"messageType\":0,"
+ "\"readFlag\":0,"
+ "\"sendTime\":1469072904000,"
+ "\"content\":\" \","
+ "\"updateTime\":1469072904000},"
+ "{\"messageNo\":\"Me201607211146458551987\","
+ "\"memberNo\":\"AD2016070812145640900000003\","
+ "\"mobileNo\":\"151****1314\","
+ "\"nickname\":\"远方\","
+ "\"headPath\":\"/fileupload/memberImage/83788978A0614007BF7F5D20F668088A1468667650848.jpg\","
+ "\"messageType\":0,"
+ "\"readFlag\":0,"
+ "\"sendTime\":1469072805000,"
+ "\"content\":\"有6\","
+ "\"updateTime\":1469072805000},{\"messageNo\":\"Me201607191730505629442\",\"memberNo\":\"AD2016070810124275700000002\",\"mobileNo\""
+ ":\"156****3913\",\"nickname\":\"呵呵\",\"headPath\":\"/fileupload/memberImage/FD5DAE12CB7944"
+ "7BB5263EB0EE4E75F41469069984778.jpg\",\"messageType\":0,\"readFlag\":0,\"sendTime\":1468"
+ "920650000,\"content\":\"额\",\"updateTime\":1468920650000},{\"messageNo\":\"Me2016071610"
+ "49255579387\",\"memberNo\":\"AD2016070812145640900000003\",\"mobileNo\":\"151****1314\",\"nic"
+ "kname\":\"远方\",\"headPath\":\"/fileupload/memberImage/83788978A0614007BF7F5D20F668088A14686"
+ "67650848.jpg\",\"messageType\":1,\"readFlag\":0,\"sendTime\":1468637365000,\"content\":\"111\",\"upda"
+ "teTime\":1468637365000},{\"messageNo\":\"Me201607161037444613493\",\"memberNo\":\"AD20160708121456409"
+ "00000003\",\"mobileNo\":\"151****1314\",\"nickname\":\"远方\",\"headPath\":\"/fileupload/memberImage/8"
+ "3788978A0614007BF7F5D20F668088A1468667650848.jpg\",\"messageType\":0,\"readFlag\":0,\"sendTime\":146"
+ "8636664000,\"content\":\"哈哈哈\",\"updateTime\":1468636664000}],\"otherData\":null}}";
}
存储数据用的 3个 Setter and Getter封装类(因为Json数据有3层所以有3个) Info_util.java:
package com.accord.fastjson;
public class Info_util {
private int status;
private String msg, data;
@Override
public String toString() {
return " status=" + status + ", msg=" + msg + ", data=" + data;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
Info_data_util.java
package com.accord.fastjson;
public class Info_data_util {
private int start, limit, total;
private String rows;
@Override
public String toString() {
return " start=" + start + ", limit=" + limit + ", total=" + total
+ ", rows=" + rows;
}
public String getRows() {
return rows;
}
public void setRows(String rows) {
this.rows = rows;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
}
Info_array_util.java
package com.accord.fastjson;
public class Info_array_Util {
private String messageNo, memberNo, mobileNo, nickname, headPath, content;
private int messageType, readFlag;
private long sendTime, updateTime;
@Override
public String toString() {
return " messageNo=" + messageNo + ", memberNo="
+ memberNo + ", mobileNo=" + mobileNo + ", nickname="
+ nickname + ", headPath=" + headPath + ", content=" + content
+ ", messageType=" + messageType + ", readFlag=" + readFlag
+ ", sendTime=" + sendTime + ", updateTime=" + updateTime ;
}
public String getMessageNo() {
return messageNo;
}
public void setMessageNo(String messageNo) {
this.messageNo = messageNo;
}
public String getMemberNo() {
return memberNo;
}
public void setMemberNo(String memberNo) {
this.memberNo = memberNo;
}
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getHeadPath() {
return headPath;
}
public void setHeadPath(String headPath) {
this.headPath = headPath;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getMessageType() {
return messageType;
}
public void setMessageType(int messageType) {
this.messageType = messageType;
}
public int getReadFlag() {
return readFlag;
}
public void setReadFlag(int readFlag) {
this.readFlag = readFlag;
}
public long getSendTime() {
return sendTime;
}
public void setSendTime(long sendTime) {
this.sendTime = sendTime;
}
public long getUpdateTime() {
return updateTime;
}
public void setUpdateTime(long updateTime) {
this.updateTime = updateTime;
}
}
然后要用的工具类,已经写好,其他项目也可以直接用,无需改动。
Fast.java
package com.accord.fastjson;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
/**
* 然后要用的工具类,已经写好,其他项目也可以直接用,无需改动。
* @author 王久印
* 2018年2月6日
*/
public class Fast {
/**
* 解析JsonObject数据
*
* @param jsonString
* Json格式字符串
* @param cls
* 封装类
*
*/
public static <T> T parseObject(String jsonString, Class<T> cls) {
T t = null;
try {
t = JSON.parseObject(jsonString, cls);
} catch (Exception e) {
e.printStackTrace();
}
return t;
}
/**
* 解析JsonArray数据
*
* @param jsonString
* @param cls
* @return
*/
public static <T> List<T> parseArray(String jsonString, Class<T> cls) {
List<T> list = new ArrayList<T>();
try {
list = JSON.parseArray(jsonString, cls);
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
* 解析JsonArray数据,返回Map类型的List
*
* @param jsonString
* @return
*/
public static List<Map<String, Object>> parseObjectListKeyMaps(
String jsonString) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
try {
list = JSON.parseObject(jsonString,
new TypeReference<List<Map<String, Object>>>() {
});
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}
现在就可以解析Json数据了:
Main.java
package com.accord.fastjson;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
Info_util iu = new Info_util();
Info_data_util du = new Info_data_util();
List<Info_array_Util> olist = new ArrayList<Info_array_Util>();
iu = Fast.parseObject(JsonString.JsonStringValues, Info_util.class);//取得第一层JSONObject
du = Fast.parseObject(iu.getData(), Info_data_util.class);//取得第二层JSONObject
olist = Fast.parseArray(du.getRows(), Info_array_Util.class);//取得第三层JSONArray
/**
* 打印解析结果
*/
StringBuffer bu = new StringBuffer();
for (int i = 0; i < olist.size(); i++) {
bu.append("jsonArray第" + (i + 1) + "条数据:\n" + olist.get(i).toString() + "\n\n");
}
System.out.println("bu:" + bu);
System.out.println("jsonObject数据:\n\n" + iu.toString() + "\n\n" + du.toString() + "\n\n\n\n" + "jsonArray数据:\n" + "\n" + bu);
}
}
除去必要的3个封装类,解析Json的就那么三行代码,如果Json数据结构简单甚至可能只需要一行代码。
上一篇: 使用fastjson工具类json字符串和对象之间的转换
下一篇: (1)Flink学习-开始篇