fastjson与jackson解析json数据对比
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/*
*json字符串数据
* { //json对象,无key(键)
"code": 200,
"curTime": 1647840792931,
"data": {//json对象,key(键):即该json对象名字叫data
"total": "3196",
"list": [//json数组,Key(键):即该json数组名字叫list
{
"musicrid": "MUSIC_202132722",
"barrage": "0",
"artist": "等什么君(邓寓君)&FOX胡天渝",
"mvpayinfo": {
"play": "0",
"vid": "13703837",
"download": "0"
},
"isstar": 0,
"rid": 202132722,
"album": "予·君",
"albumid": "24792577",
"name": "踏雪",
"payInfo": {
"play": "1100",
"overseas_nplay": "11111",
"feeType": {
"song": "1",
"album": "0",
"vip": "1",
"bookvip": "0"
}
}
},....还有...
]
},
"msg": "success",
"profileId": "site",
"reqId": "f2d9674487bfba85c5dbb6234ffe67fd",
"tId": ""
}
*
* */
public class Test {
public static void main(String[] args) {
String jsonString = null;//json字符串数据
//fastjson解析json
JSONObject jsonObj = JSONObject.parseObject(jsonString);//解析json对象
JSONArray jsonArray = jsonObj.getJSONObject("data").getJSONArray("list");//获取到json数组
//上面的或者这样写一步获取到json数组
//JSONArray jsonArray = JSONObject.parseObject(jsonString).getJSONObject("data").getJSONArray("list");//获取到json数组
for (int i = 0; i < jsonArray.size();i++) {//遍历json数组
String name = jsonArray.getJSONObject(i).getString("name");//歌曲名
String rid = jsonArray.getJSONObject(i).getString("rid");//rid
String artist = jsonArray.getJSONObject(i).getString("artist");//歌手
}
//=====================================================================================
//jackson解析json
ObjectMapper objectMapper = new ObjectMapper();//创建
JsonNode jsonNode = objectMapper.readTree(jsonString).get("data").get("list");获取到json数组
//上面的或者这样写一步获取到jsonNode
//JsonNode jsonNode = new ObjectMapper().readTree(jsonString).get("data").get("list");
for (int i = 0; i < jsonNode.size(); i++) {//遍历
String name = jsonNode.get(i).get("name").toString();//歌曲名
String rid = jsonNode.get(i).get("rid").toString();//rid
String artist = jsonNode.get(i).get("artist").toString();//歌手
}
//foreach(增强型for循环)遍历写法
for (JsonNode i:jsonNode) {//遍历
String name = i.get("name").toString();//歌曲名
String rid = i.get("rid").toString();//rid
String artist = i.get("artist").toString();//歌手
}
}
}