欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java遍历json字符串取值的实例

程序员文章站 2024-01-27 13:25:40
java遍历json字符串,取得相应kv值时,各种麻烦,比如将json中的list取出来转为jsonarray,再将list中的object转化为map,再取值(之前的做法...

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字符串取值的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。