Java遍历json字符串取值的实例
java遍历json字符串,取得相应KV值时,各种⿇烦,⽐如将json中的list取出来转为JSONArray,再将list中的object转化为map,再取值(之前的做法),仙⼦啊通过阿⾥的fastjson,可以很⽅便的直接将str转化为JSONArray,再将⾥⾯的object强转为JSONObject,然后再通过Integer(“key”)和String(“key”)等取值。
JSONArray json = (JSONArray) JSONArray.parse(str);
for (Object obj : json) {
JSONObject jo = (JSONObject)obj;
int status = jo.getInteger("status");
String message= jo.getString("message");
System.out.println("status---" + status + "---message---" + message);
}
1.当json字符串中有数组和map对象,遍历数据,数据格式如下:
[
{
"status":0,
"tags":[
"check:ntp"
],
"timestamp":1492151922.198,
"check":"datadog.agent.check_status",
"host_name":"song-2",
"message":null,
"id":2
},
{
"status":0,
"tags":null,
"timestamp":1492151922.2325,
"check":"datadog.agent.up",
"host_name":"song-2",
"message":null,
"id":5
}
]
解析上⾯json字符串数据,如果不使⽤如fastjson或者Gson时,解析⽅法如下:
⽅法⼀
/**
* 主机详情中,异常错误信息的报错的平台服务状态和message
* @param str
* @return
* @throws Exception
*/
private List<Map<String,String>> operStr(String str) throws Exception{
List<Map<String,String>> mList = new ArrayList<Map<String,String>>();//探针开启的服务名list
JSONArray json = (JSONArray) JSONArray.parse(str);
Map<String,Object> objMap = null;
Map<String,String> resMap = null;
for (Object obj : json) {
objMap = Obj2Map(obj);
@SuppressWarnings("unchecked")
Map<String,Object> mObj = (Map<String, Object>) ("map");
int status = (Integer) ("status");
if(status != 0){
fastjson字符串转数组resMap = new HashMap<String,String>();
switch (status) {
case 1:
resMap.put("status","WARNING");
break;
case 2:
resMap.put("status","ERROR");
break;
case 3:
resMap.put("status","CRIT");
break;
default:
break;
}
resMap.put("serviceName", ((String) ("check")).split("\\.")[0]);
resMap.put("msg", (("message"));
mList.add(resMap);
}
}
return mList;
}
/**
* object转map
* @param obj
* @return
* @throws Exception
*/
public Map<String,Object> Obj2Map(Object obj) throws Exception{
if(obj == null){
return null;
}
Map<String,Object> map=new HashMap<String, Object>();
Field[] fields = Class().getDeclaredFields();
for(Field field:fields){
field.setAccessible(true);
map.Name(), (obj));
}
return map;
}
⽅法⼆
/**
* 主机详情中,异常错误信息的报错的平台服务状态和message
* @param str
* @return
* @throws Exception
*/
private List<Map<String,String>> operStr(String str) throws Exception{
List<Map<String,String>> mList = new ArrayList<Map<String,String>>();//探针开启的服务名list
JSONArray json = (JSONArray) JSONArray.parse(str);
Map<String,String> resMap = null;
for (Object obj : json) {
JSONObject jo = (JSONObject)obj;
int status = jo.getInteger("status");
if(status != 0){
resMap = new HashMap<String,String>();
switch (status) {
case 1:
resMap.put("status","WARNING");
break;
case 2:
resMap.put("status","ERROR");
break;
case 3:
resMap.put("status","CRIT");
break;
default:
break;
}
resMap.put("serviceName", (jo.getString("check")).split("\\.")[0]);
resMap.put("msg", jo.getString("message"));
mList.add(resMap);
}
}
return mList;
}
2.当json字符串中是数组包含数组时候,遍历数据,数据格式如下:
[
[
"haproxy",
"haproxy",
0,
"ERROR",
"swdfghyjuikl",
{
}
],
[
"gearmand",
"gearmand",
0,
"ERROR",
"'Found no valid connections in list: [<GearmanConnection localhost:4730 connected=False>]'",
{
"version":"[8, 4, 20]"
}
]
]
⽅法⼀
/**
* 通过查询agentChecksStr解析得到异常信息
* @param agentChecksStr
* @return
*/
private List<Map<String,String>> getExceptInfoFromAgentChecks(String agentChecksStr){
List<Map<String,String>> mList = new ArrayList<Map<String,String>>();//探针开启的服务名list
//mList 主机详情中,异常错误信息的报错的平台服务状态和message
Object jsonArray = JSONArray.parse(agentChecksStr);
@SuppressWarnings("unchecked")
List<List<Object>> list= (List<List<Object>>) jsonArray;
Map<String,String> map = null;
for(int i=0;i<list.size();i++){
map = new HashMap<String,String>();
String status = (i).get(3).toString();
if(!status.equals("OK")){
String serviceName = (i).get(0).toString();
String msg = (i).get(4).toString();
map.put("serviceName", serviceName);
map.put("status", status);
map.put("msg", msg);
mList.add(map);
}
}
return mList;
}
⽅法⼆
/**
* 通过查询agentChecksStr解析得到异常信息
* @param agentChecksStr
* @return
*/
private List<Map<String,String>> getExceptInfoFromAgentChecks(String agentChecksStr){
//探针开启的服务名list
List<Map<String,String>> mList = new ArrayList<Map<String,String>>();
JSONArray jsonArray = (JSONArray) JSONArray.parse(agentChecksStr);
Map<String,String> map = null;
for (Object obj : jsonArray) {
map = new HashMap<String,String>();
JSONArray ja = (JSONArray)obj;
String status = ja.getString(3);
if(!status.equals("OK")){
String serviceName = ja.getString(0);
String msg = ja.getString(4);
map.put("serviceName", serviceName);
map.put("status", status);
map.put("msg", msg);
mList.add(map);
}
}
return mList;
}
Gson将json字符串转化为json对象:
le.gson.Gson;
le.gson.JsonArray;
le.gson.JsonElement;
le.gson.JsonObject;
le.gson.JsonParser;
public class MainTest {
public static void main(String[] args) throws Exception{
String jsonstr0 = "{\"alarmDetails\":{\"conditionDetails\":{\"alarmId\":7,\"alarmNodataNotifyTime\":1,\"alarmNowSeriesWaitTime\":2},\"conditionStatic\":{\"alarmId\":7,\"conditionAggregate\":\"avg\",\"conditionOperator\":1,\"conditionThresholdTime\":5,\"condition    String jsonstr1 = "{\"alarmDetails\":{\"conditionDetails\":{\"alarmId\":7,\"alarmNodataNotifyTime\":1,\"alarmNowSeriesWaitTime\":2},\"conditionStatic\":{\"alarmId\":7,\"conditionAggregate\":\"avg\",\"conditionOperator\":1,\"conditionThresholdTime\":5,\"condition    Set<String> set = new HashSet<String>();
set.add(jsonstr0);
set.add(jsonstr1);
Gson gs = new Gson();
List<Object> eventList = new ArrayList<Object>();
for (String str : set) {
JsonObject returnData = new JsonParser().parse(str).getAsJsonObject();
JsonObject ad = ("alarmDetails").getAsJsonObject();
JsonObject vd = ("validataDetails").getAsJsonObject();
JsonArray vm = vd.get("validataMerges").getAsJsonArray();
JsonArray nf = ad.get("notify").getAsJsonArray();
JsonObject v = ad.get("view").getAsJsonObject();
String validataTimeSeconds = vd.get("validataTimeSeconds").toString();
for (JsonElement je : vm) {
eventList.add(je);
}
}
for (Object obj : eventList) {
String inParam = gs.toJson(obj);
System.out.println(inParam);
}
System.out.Json(eventList));
}
}
//获取设备信息(只有硬件设备和虚拟设备有)
HashMap<String,String> paramMap = new HashMap<String,String>();
paramMap.put("hostid", mHostId);
paramMap.put("ptype", Ptype());
paramMap.put("type_flag", TypeFlag());
paramMap.put("api_key", apikey);
String resStr = (DEVICE_INFO_URL, paramMap);
JSONObject jobj = JSON.parseObject(resStr);
JSONObject obj = (("result");
if(obj.size() != 0){
String restr = ("result").toString();
DeviceInfoDto deviceInfoDto = new Gson().fromJson(restr, DeviceInfoDto.class);
dto.setDeviceInfo(deviceInfoDto);
}
List<Map<Integer, Long>> result = new ArrayList<Map<Integer, Long>>();
Map<String, String> timeMap = null;
List<Map<String, String>> timeArr = new ArrayList<Map<String, String>>();
for (int j = 0; j < result.size(); j++) {
timeMap = new HashMap<String, String>();
if (j == result.size() - 1) {
timeMap.put("startTime",(j).(j).keySet().iterator().next()) + "");
timeMap.put("endTime", System.currentTimeMillis() + "");
} else {
timeMap.put("startTime", (j).(j).keySet().iterator().next()) + "");
timeMap.put("endTime", ((j+1).(j+1).keySet().iterator().next()) - 1) + "");
}
timeMap.put("hostName", "*");
//1:info,2:error,3:success,4:warning
Integer key = (j).keySet().iterator().next();
if (key == 1) {
timeMap.put("status", "info");
} else if (key == 2) {
timeMap.put("status", "error");
} else if (key == 3) {
timeMap.put("status", "success");
} else if (key == 4) {
timeMap.put("status", "warning");
}
timeArr.add(timeMap);
}
以上这篇Java遍历json字符串取值的实例就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。