JAVA가 JSON 문자열을 가로 지르고 해당 KV 값을 얻을 때 JSON에서 목록을 jsonArray로 변환 한 다음 목록의 객체를 맵으로 변환 한 다음 값 (이전 연습)과 같은 다양한 문제가 발생합니다. 요정은 Alibaba의 Fastjson을 통해 str를 JsonArray로 쉽게 변환 한 다음 객체를 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 ( "상태"); 문자열 메시지 = jo.getString ( "메시지"); System.out.println ( "상태 ---" + 상태 + "--- 메시지 ---" + 메시지);}1. JSON 문자열에 배열 및 맵 객체가 있으면 데이터를 가로 지르며 데이터 형식은 다음과 같습니다.
[{ "status": 0, "tags": [ "check : ntp"], "timestamp": "timeStamp": 1492151922.198, "check": "datadog.agent.check_status", "host_name": "송 -2", "메시지": null ":"2}, { "상태": 0, tag " "타임 스탬프": 1492151922.2325, "check": "datadog.agent.up", "host_name": "song-2", "message": null, "id": 5}]위의 JSON 문자열 데이터를 구문 분석 할 때 FastJSON 또는 GSON을 사용하지 않으면 구문 분석 방법은 다음과 같습니다.
방법 1
/** * 호스트 세부 사항에서 오류 * @param str * @return * @throws 예외 */개인 목록 <string, string, string (String str)은 예외 {list <map <string, string >> mlist = new arraylist <map <string, string >> (); jsonarray.parse (str); Map <String, Object> objmap = null; Map <String, String> resmap = null; for (object obj : json) {objmap = obj2map (obj); @SuppressWarnings ( "선택 취소")지도 <String, Object> mobj = (Map <String, Object>) objmap.get ( "map"); int status = (정수) mobj.get ( "상태"); if (status! = 0) {resmap = new Hashmap <String, String> (); switch (status) {case 1 : resmap.put ( "상태", "경고"); 부서지다; 사례 2 : resmap.put ( "status", "error"); 부서지다; 사례 3 : resmap.put ( "상태", "Crit"); 부서지다; 기본값 : 브레이크; } resmap.put ( "serviceName", ((string) mobj.get ( "Check")). split ( "//.") [0]; resmap.put ( "msg", (string) mobj.get ( "message")); mlist.add (resmap); }} return mlist; } / ** * Map * @param obj * @return * @throws Exception * / public map <string, object> obj2map (Object obj)는 예외 {if (obj == null) {return null; } map <String, object> map = new Hashmap <String, Object> (); 필드 [] fields = obj.getClass (). getDeclaredFields (); for (필드 필드 : 필드) {field.setAccessible (true); map.put (field.getName (), field.get (obj)); } 리턴 맵; }방법 2
/** * 호스트 세부 사항에서, 오류 * @param st * @return * @throws 예외 */개인 목록 <string, string, string (String str)은 예외 {list <map <string, string >> mlist = new arraylist <map <string, string >> (); jsonarray.parse (str); Map <String, String> resmap = null; for (object obj : json) {jsonobject jo = (jsonobject) obj; int status = jo.getInteger ( "상태"); if (status! = 0) {resmap = new Hashmap <String, String> (); switch (status) {case 1 : resmap.put ( "상태", "경고"); 부서지다; 사례 2 : resmap.put ( "status", "error"); 부서지다; 사례 3 : resmap.put ( "상태", "Crit"); 부서지다; 기본값 : 브레이크; } 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 ","목록에서 유효한 연결이 없음 : [<GearmanConnection localHost : 4730 Connected = false>] ","버전 ":"8, 4, 20]}]방법 1
/** * 에이전트를 쿼리하여 예외 정보 가져 오기 * @param agentchecksstr * @return */private list <map <string, string >> getExceptInfofromagentCheck (String agentchecksStr) {list <map <string, string >> mlist = new arraylist <map <string, string >> 및 예외 오류 메시지 보고서 오류 객체 jsonarray = jsonarray.parse (agentchecksstr); @SuppressWarnings ( "선택 취소") 목록 <list <객체 >> list = (list <list <객체 >>) jsonarray; map <string, String> map = null; for (int i = 0; i <list.size (); i ++) {map = new Hashmap <String, String> (); 문자열 상태 = list.get (i) .get (3) .toString (); if (! status.equals ( "ok")) {String serviceName = list.get (i) .get (0) .toString (); 문자열 msg = list.get (i) .get (4) .toString (); map.put ( "ServiceName", ServiceName); map.put ( "상태", 상태); map.put ( "msg", mlist.add (map);}} return mlist;}방법 2
/** * 에이전트를 쿼리하여 예외 정보 가져 오기 * @param agentchecksstr * @return */private list <map <string, string >> getExceptInfofromagentCheck (String AgentchecksStr) {// probe enabled service name list <map <string, string >> mlist = new arraylist <map >> (); jsonarray jsonarray = (jsonarray) jsonarray.parse (agentchecksstr); map <string, String> map = null; for (object obj : jsonarray) {map = new Hashmap <String, String> (); jsonarray ja = (jsonarray) obj; 문자열 상태 = ja.getString (3); if (! status.equals ( "ok")) {String serviceName = ja.getString (0); 문자열 msg = ja.getString (4); map.put ( "ServiceName", ServiceName); map.put ( "상태", 상태); map.put ( "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 {String jsonstont0 = {string jsonstr0 = "{/"AlarmDetails/": {/"ConditionDetails/": {/"alarmid/": 7,/"AlarmNodatanotifytime/": 1,/"AlarmNowserieswaittime/": 2},/ "컨디셔티스틱/": {/"alarmid/": 7,/"컨디셔닝/":/"avg/",/"conditionoperator/": 1,/"조건 thresholdtime/": 5,/"조건 thresholdValue/":/"123/"},/"metricDetails/": {/"alarmid/": 7,/"metricaggregater/":/"avg/",/"metricby/":/ "host/",/"metricexcludetag/":/"호스트 : paas-177/",/"metricname/":/"system.cpu.user/",/"metricq/":/"avg : system.cpu.user { #Address : wuhan,! host : paas-177} by {host}/",/"metrictag/":/"#주소 : wuhan/"},/"notify/": [{/"alarmid/": 7,/"notifychann el/": 5,/"notifyuserid/": 1}, {/"alarmid/": 7,/"notifyChannel/": 5,/"notifyUserId/": 2}],/"View/": {/"alarmexpression/":/"a vg (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/":/"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/":/"#주소 : wuhan/",/"updateTime/":/"2017-06-29 15 : 49 : 18.0/"}},/"alarmid/": 7,/"allmark/": {/"avg : system.cpu.user {host : cfeng-4,#주소 : wuhan,! 호스트 : 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/"}}},/"contortype/": 3,/"UsemetricUnit/":/"cents/",/"validatadetails/": {/"status/": 0,/"validatamerges/": [{/"alarmmarkdto/": {/"changeputtime/": true,/"lastputtsdbtime/":/"ac 655349,/"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/":: /"호스트 : cfeng-4/",/"validatanodata/": {/"currenttime/": 1499655349,/"isnodata/": false,/"lastsucc EssCheckTime/": 1499655349,/"Series/":/"avg : System.cpu.user {host : cfeng-4,#주소 : wuhan,! host : p AAS-177}/",/"tag/": {/"host/":/"cfeng-4/",/"#address/":/"wuhan/",/"! host/":/"paas-177/"},/"thre sholdtime/": 60},/"validatastatic/": {/"convertothresholdvalue/": 123.0,/"end/": 1499655343,/"inte rvalaggregator/":/"avg/",/"isalart/": true,/"operator/": 1,/"series/":/"avg : system.cpu.user {host : CFENG-4,#주소 : WUHAN,! 호스트 : PAAS-177}/",/"start/": 1499655043,/"sysunit/":/" %/",/"tag/"" : {/"#주소/":/"wuhan/",/"host/":/"cfeng-4/",/"! host/":/"paas-177/"},/"thresholdtime/": 300,/" ThresholdValue/":/"123/",/"value/": 5.715769243240357}],/"validatatimeseconds/": 1499655349}}"; 문자열 jsonstr1 = "{/"AlarmDetails/": {/"ConditionDetails/": {/"alarmid/": 7,/"AlarmNodatanotifytime/": 1,/"AlarmNowserieswaittime/": 2},/ "컨디셔티스틱/": {/"alarmid/": 7,/"컨디셔닝/":/"avg/",/"conditionoperator/": 1,/"조건 thresholdtime/": 5,/"조건 thresholdValue/":/"123/"},/"metricDetails/": {/"alarmid/": 7,/"metricaggregater/":/"avg/",/"metricby/":/ "host/",/"metricexcludetag/":/"호스트 : paas-177/",/"metricname/":/"system.cpu.user/",/"metricq/":/"avg : system.cpu.user { #Address : wuhan,! host : paas-177} by {host}/",/"metrictag/":/"#주소 : wuhan/"},/"notify/": [{/"alarmid/": 7,/"notifychann el/": 5,/"notifyuserid/": 1}, {/"alarmid/": 7,/"notifyChannel/": 5,/"notifyUserId/": 2}],/"View/": {/"alarmexpression/":/"a vg (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/":/"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/":/"#주소 : wuhan/",/"updateTime/":/"2017-06-29 15 : 49 : 18.0/"}},/"alarmid/": 7,/"allmark/": {/"avg : system.cpu.user {host : cfeng-4,#주소 : wuhan,! 호스트 : 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/"}}},/"contortype/": 3,/"UsemetricUnit/":/"cental/",/"validatadetails/": {/"status/": 0,/"validatamerges/": [{/"alarmmarkdto/": {/"changeputtime/": true,/"lastputtsdbtime/": 1499655374,/"149655374,/" 655379,/"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/":: /"호스트 : cfeng-4/",/"validatanodata/": {/"currentTime/": 1499655379,/"IsNodata/": false,/"lastsucc EssCheckTime/": 1499655379,/"series/":/"avg : System.cpu.user {host : cfeng-4,#주소 : wuhan,! host : p AAS-177}/",/"tag/": {/"host/":/"cfeng-4/",/"#address/":/"wuhan/",/"! host/":/"paas-177/"},/"thre sholdtime/": 60},/"validatastatic/": {/"convertothresholdvalue/": 123.0,/"end/": 1499655374,/"inte rvalaggregator/":/"avg/",/"isalart/": true,/"operator/": 1,/"series/":/"avg : system.cpu.user {host : CFENG-4,#주소 : WUHAN,! 호스트 : PAAS-177}/",/"start/": 1499655074,/"sysunit/":/" %/",/"tag/"" : {/"#주소/":/"wuhan/",/"host/":/"cfeng-4/",/"! host/":/"paas-177/"},/"thresholdtime/": 300,/" thresholdValue/":/"123/",/"value/":5.089640821729388}}],/"validataTimeSeconds/":1499655379}}"; <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 ( "보기"). getAsjsonObject (); 문자열 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); 복원 = jobj.get ( "결과"). toString (); deviceinfodto deviceinfodto = new gson (). fromjson (vest, deviceinfodto.class); dto.setdeviceinfo (deviceinfodto);}
List <map <integer, long >> result = new arraylist <map <integer, long >> (); map <문자열, 문자열> 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 ()) + ""); timemap.put ( "endtime", (result.get (j+1) .get (result.get (j+1) .keyset (). iterator (). next ()) -1)+"");} timemap.put ( "hostname", "*"); // 1 : info, 2 : error, 3 : 4 : warleninteger 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) { "status"( "success"); timemap.put ( "status", "경고");} timearr.add (timemap);}JSON 문자열 값을 가로 지르는 Java의 위의 예는 내가 공유하는 모든 컨텐츠입니다. 나는 당신이 당신에게 참조를 줄 수 있기를 바랍니다. 그리고 당신이 wulin.com을 더 지원할 수 있기를 바랍니다.