中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java遍歷json字符串取值的實例

發布時間:2020-10-03 21:03:19 來源:腳本之家 閱讀:388 作者:u010466329 欄目:編程語言

java遍歷json字符串,取得相應KV值時,各種麻煩,比如將json中的list取出來轉為JSONArray,再將list中的object轉化為map,再取值(之前的做法),仙子啊通過阿里的fastjson,可以很方便的直接將str轉化為JSONArray,再將里面的object強轉為JSONObject,然后再通過obj.getInteger(“key”)和obj.getString(“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>) objMap.get("map");
      int status = (Integer) mObj.get("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", ((String) mObj.get("check")).split("\\.")[0]);
        resMap.put("msg", (String)mObj.get("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 = obj.getClass().getDeclaredFields();
    for(Field field:fields){
      field.setAccessible(true);
      map.put(field.getName(), field.get(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 = list.get(i).get(3).toString();
      if(!status.equals("OK")){
        String serviceName = list.get(i).get(0).toString();
        String msg = list.get(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對象:

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.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,\"conditionThresholdValue\":\"123\"},\"metricDetails\":{\"alarmId\":7,\"metricAggregater\":\"avg\",\"metricBy\":\"host\",\"metricExcludeTag\":\"host:paas-177\",\"metricName\":\"system.cpu.user\",\"metricQ\":\"avg:system.cpu.user{#address:wuhan,!host:paas-177}by{host}\",\"metricTag\":\"#address:wuhan\"},\"notify\":[{\"alarmId\":7,\"notifyChannel\":5,\"notifyUserId\":1},{\"alarmId\":7,\"notifyChannel\":5,\"notifyUserId\":2}],\"view\":{\"alarmExpression\":\"avg(last_5m)avg:system.cpu.user{#address:wuhan,!host:paas-177}by{host}>123.0\",\"alarmId\":7,\"alarmLastValue\":\"UP\",\"alarmName\":\"static_metric\",\"alarmStatus\":1,\"alarmType\":2,\"alarmTypeJoin\":3,\"createTime\":\"2017-06-28 17:25:52.0\",\"createUserId\":1,\"isDisable\":false,\"lastAlarmTime\":\"2017-06-28 17:25:27.0\",\"metricName\":\"system.cpu.user\",\"metricTag\":\"#address:wuhan\",\"updateTime\":\"2017-06-29 15:49:18.0\"}},\"alarmId\":7,\"allMark\":{\"avg:system.cpu.user{host:cfeng-4,#address:wuhan,!host:paas-177}\":{\"changePutTime\":true,\"lastPutTsdbTime\":1499655343,\"lastSuccessCheckTime\":1499655349,\"series\":\"avg:system.cpu.user{host:cfeng-4,#address:wuhan,!host:paas-177}\",\"tagMap\":{\"host\":\"cfeng-4\",\"#address\":\"wuhan\",\"!host\":\"paas-177\"}}},\"joinType\":3,\"useMetricUnit\":\"percent\",\"validataDetails\":{\"status\":0,\"validataMerges\":[{\"alarmMarkDto\":{\"changePutTime\":true,\"lastPutTsdbTime\":1499655343,\"lastSuccessCheckTime\":1499655349,\"series\":\"avg:system.cpu.user{host:cfeng-4,#address:wuhan,!host:paas-177}\",\"tagMap\":{\"host\":\"cfeng-4\",\"#address\":\"wuhan\",\"!host\":\"paas-177\"}},\"status\":0,\"tag\":\"host:cfeng-4\",\"validataNodata\":{\"currentTime\":1499655349,\"isNodata\":false,\"lastSuccessCheckTime\":1499655349,\"series\":\"avg:system.cpu.user{host:cfeng-4,#address:wuhan,!host:paas-177}\",\"tag\":{\"host\":\"cfeng-4\",\"#address\":\"wuhan\",\"!host\":\"paas-177\"},\"thresholdTime\":60},\"validataStatic\":{\"converToThresholdValue\":123.0,\"end\":1499655343,\"intervalAggregator\":\"avg\",\"isAlart\":true,\"operator\":1,\"series\":\"avg:system.cpu.user{host:cfeng-4,#address:wuhan,!host:paas-177}\",\"start\":1499655043,\"sysUnit\":\"percent\",\"tag\":{\"#address\":\"wuhan\",\"host\":\"cfeng-4\",\"!host\":\"paas-177\"},\"thresholdTime\":300,\"thresholdValue\":\"123\",\"value\":5.715769243240357}}],\"validataTimeSeconds\":1499655349}}";
    String jsonstr1 = "{\"alarmDetails\":{\"conditionDetails\":{\"alarmId\":7,\"alarmNodataNotifyTime\":1,\"alarmNowSeriesWaitTime\":2},\"conditionStatic\":{\"alarmId\":7,\"conditionAggregate\":\"avg\",\"conditionOperator\":1,\"conditionThresholdTime\":5,\"conditionThresholdValue\":\"123\"},\"metricDetails\":{\"alarmId\":7,\"metricAggregater\":\"avg\",\"metricBy\":\"host\",\"metricExcludeTag\":\"host:paas-177\",\"metricName\":\"system.cpu.user\",\"metricQ\":\"avg:system.cpu.user{#address:wuhan,!host:paas-177}by{host}\",\"metricTag\":\"#address:wuhan\"},\"notify\":[{\"alarmId\":7,\"notifyChannel\":5,\"notifyUserId\":1},{\"alarmId\":7,\"notifyChannel\":5,\"notifyUserId\":2}],\"view\":{\"alarmExpression\":\"avg(last_5m)avg:system.cpu.user{#address:wuhan,!host:paas-177}by{host}>123.0\",\"alarmId\":7,\"alarmLastValue\":\"UP\",\"alarmName\":\"static_metric\",\"alarmStatus\":1,\"alarmType\":2,\"alarmTypeJoin\":3,\"createTime\":\"2017-06-28 17:25:52.0\",\"createUserId\":1,\"isDisable\":false,\"lastAlarmTime\":\"2017-06-28 17:25:27.0\",\"metricName\":\"system.cpu.user\",\"metricTag\":\"#address:wuhan\",\"updateTime\":\"2017-06-29 15:49:18.0\"}},\"alarmId\":7,\"allMark\":{\"avg:system.cpu.user{host:cfeng-4,#address:wuhan,!host:paas-177}\":{\"changePutTime\":true,\"lastPutTsdbTime\":1499655374,\"lastSuccessCheckTime\":1499655379,\"series\":\"avg:system.cpu.user{host:cfeng-4,#address:wuhan,!host:paas-177}\",\"tagMap\":{\"host\":\"cfeng-4\",\"#address\":\"wuhan\",\"!host\":\"paas-177\"}}},\"joinType\":3,\"useMetricUnit\":\"percent\",\"validataDetails\":{\"status\":0,\"validataMerges\":[{\"alarmMarkDto\":{\"changePutTime\":true,\"lastPutTsdbTime\":1499655374,\"lastSuccessCheckTime\":1499655379,\"series\":\"avg:system.cpu.user{host:cfeng-4,#address:wuhan,!host:paas-177}\",\"tagMap\":{\"host\":\"cfeng-4\",\"#address\":\"wuhan\",\"!host\":\"paas-177\"}},\"status\":0,\"tag\":\"host:cfeng-4\",\"validataNodata\":{\"currentTime\":1499655379,\"isNodata\":false,\"lastSuccessCheckTime\":1499655379,\"series\":\"avg:system.cpu.user{host:cfeng-4,#address:wuhan,!host:paas-177}\",\"tag\":{\"host\":\"cfeng-4\",\"#address\":\"wuhan\",\"!host\":\"paas-177\"},\"thresholdTime\":60},\"validataStatic\":{\"converToThresholdValue\":123.0,\"end\":1499655374,\"intervalAggregator\":\"avg\",\"isAlart\":true,\"operator\":1,\"series\":\"avg:system.cpu.user{host:cfeng-4,#address:wuhan,!host:paas-177}\",\"start\":1499655074,\"sysUnit\":\"percent\",\"tag\":{\"#address\":\"wuhan\",\"host\":\"cfeng-4\",\"!host\":\"paas-177\"},\"thresholdTime\":300,\"thresholdValue\":\"123\",\"value\":5.089640821729388}}],\"validataTimeSeconds\":1499655379}}";
    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 = returnData.get("alarmDetails").getAsJsonObject();
      JsonObject vd = returnData.get("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) {
        je.getAsJsonObject().add("view", v);
        je.getAsJsonObject().add("notify", nf);
        je.getAsJsonObject().addProperty("validataTimeSeconds", Long.parseLong(validataTimeSeconds));
        eventList.add(je);
      }
    }
    for (Object obj : eventList) {
      String inParam = gs.toJson(obj);
      System.out.println(inParam);
    }
    System.out.println(gs.toJson(eventList));
  }
}
//獲取設備信息(只有硬件設備和虛擬設備有)
HashMap<String,String> paramMap = new HashMap<String,String>();
paramMap.put("hostid", mHostId);
paramMap.put("ptype", dto.getPtype());
paramMap.put("type_flag", dto.getTypeFlag());
paramMap.put("api_key", apikey);
String resStr = HttpUtils.get(DEVICE_INFO_URL, paramMap);
JSONObject jobj = JSON.parseObject(resStr);
JSONObject obj = (JSONObject)jobj.get("result");
if(obj.size() != 0){
  String restr = jobj.get("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",result.get(j).get(result.get(j).keySet().iterator().next()) + "");
  timeMap.put("endTime", System.currentTimeMillis() + "");
} else {
  timeMap.put("startTime", result.get(j).get(result.get(j).keySet().iterator().next()) + "");
  timeMap.put("endTime", (result.get(j+1).get(result.get(j+1).keySet().iterator().next()) - 1) + "");
}
timeMap.put("hostName", "*");
//1:info,2:error,3:success,4:warning
Integer key = result.get(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字符串取值的實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

淅川县| 得荣县| 册亨县| 大化| 新乐市| 涿鹿县| 乐东| 洪湖市| 瓦房店市| 汕头市| 保山市| 广昌县| 彰化市| 张家港市| 东丽区| 永嘉县| 尤溪县| 民和| 屯留县| 利津县| 安顺市| 娱乐| 虎林市| 交口县| 巩留县| 左权县| 苗栗市| 罗甸县| 哈尔滨市| 新宾| 清丰县| 清河县| 南木林县| 祁东县| 南通市| 行唐县| 卫辉市| 双城市| 呼和浩特市| 铁岭市| 定远县|