引入 jar
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.4</version>
</dependency>
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。
< 200, {
"data": {
"netout": 0,
"cpu": 0,
"diskwrite": 0,
"pid": null,
"uptime": 0,
"template": "",
"maxmem": 4294967296,
"ha": {
"managed": 1,
"group": null,
"state": "error"
},
"status": "stopped",
"vmid": "100",
"name": "101",
"qmpstatus": "stopped",
"maxdisk": 68719476736,
"cpus": 4,
"disk": 0,
"spice": 1,
"netin": 0,
"mem": 0,
"diskread": 0
}
}, {
Cache - Control = [max - age = 0],
Connection = [Keep - Alive, Keep - Alive],
Date = [Thu, 17 Dec 2020 06: 14: 46 GMT],
Pragma = [no - cache],
Server = [pve - api - daemon / 3.0],
Content - Length = [295],
Content - Type = [application / json;charset = UTF - 8],
Expires = [Thu, 17 Dec 2020 06: 14: 46 GMT]
} >
接口返回数据图上所示.
1、获得 其中data部分 使用JSONObject.parseObject
将text解析为一个JSONObject对象并返回
JSONObject ob=JSONObject.parseObject(response.getBody());
JSONObject data=JSONObject.parseObject(ob.getString("data"));
得到的data的返回内容如下:
{
"template": "",
"vmid": "100",
"cpus": 4,
"spice": 1,
"cpu": 0,
"diskread": 0,
"netout": 0,
"uptime": 0,
"disk": 0,
"mem": 0,
"maxdisk": 68719476736,
"name": "101",
"ha": {
"managed": 1,
"state": "error"
},
"qmpstatus": "stopped",
"diskwrite": 0,
"maxmem": 4294967296,
"status": "stopped",
"netin": 0
}
如要获得vmid的属性 直接 data.getString(“vmid”); 即可。
如下解析data中带[]的json字符串
{
"data": [{
"value": "101",
"key": "name"
},{
"value": "local1:100/vm-100-disk-0.raw,size=64G",
"key": "ide0"
}, {
"value": "348613c6bafa66ab07938219a9ce2065b02c2e9f",
"key": "digest"
}]
}
首先
JSONObject[] dataZoom = new JSONObject[]{JSONObject.parseObject(response2.getBody())};
String aa= dataZoom[0].getString("data"); //获得下标为0的数组数据
转换成 JSONArray
JSONArray tableData = JSONArray.parseArray(aa);
for (int i = 0; i < tableData.size(); i++) {
JSONObject jsonObject = tableData.getJSONObject(i);
map2.put(jsonObject.getString("key"), jsonObject.getString("value"));
}