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

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

(0)

相关推荐

  • java解析任意层数json字符串的方法

    复制代码 代码如下: //解析策略,有可能是解析json字符串,有可能为数据中的图片地址,email等package cc.util.regex; public enum RegexPolicy { Json("Json"), Image("ImageFromHtml"); private String value; RegexPolicy (String value) {  this.value = value; } @Override public String

  • Java中Json字符串直接转换为对象的方法(包括多层List集合)

    使用到的类:net.sf.json.JSONObject 使用JSON时,除了要导入JSON网站上面下载的json-lib-2.2-jdk15.jar包之外,还必须有其它几个依赖包:commons-beanutils.jar,commons-httpclient.jar,commons-lang.jar,ezmorph.jar,morph-1.0.1.jar 下面是例子代码: // JSON转换 JSONObject jsonObj = JSONObject.fromObject(jsonStr

  • java json字符串转JSONObject和JSONArray以及取值的实例

    java json字符串转JSONObject和JSONArray以及取值的实例 实现代码: import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class JsonTest { public static void main(String[] args) { String joStr = "{name:\"张三\",age:\"20\"}"; //将json字符

  • java的Jackson将json字符串转换成泛型List

    Jackson,我感觉是在Java与Json之间相互转换的最快速的框架,当然Google的Gson也很不错,但是参照网上有人的性能测试,看起来还是Jackson比较快一点 Jackson处理一般的JavaBean和Json之间的转换只要使用ObjectMapper 对象的readValue和writeValueAsString两个方法就能实现.但是如果要转换复杂类型Collection如 List<YourBean>,那么就需要先反序列化复杂类型 为泛型的Collection Type. 如果

  • java的JsonObject对象提取值方法

    实例如下所示: import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import io.swagger.models.auth.In; import java.io.IOException; import java.security.KeyManagementException; import java.security.N

  • Java实现Json字符串与Object对象相互转换的方式总结

    本文实例总结了Java实现Json字符串与Object对象相互转换的方式.分享给大家供大家参考,具体如下: Json-Lib.Org.Json.Jackson.Gson.FastJson五种方式转换json类型 只列举了最省事的方式.不涉及复制情况和速度. 测试用例,一个User类,属性name,age,location.重写toString(). public class User { private String name; private Integer age; private Stri

  • Java中JSON字符串与java对象的互换实例详解

    在开发过程中,经常需要和别的系统交换数据,数据交换的格式有XML.JSON等,JSON作为一个轻量级的数据格式比xml效率要高,XML需要很多的标签,这无疑占据了网络流量,JSON在这方面则做的很好,下面先看下JSON的格式, JSON可以有两种格式,一种是对象格式的,另一种是数组对象, {"name":"JSON","address":"北京市西城区","age":25}//JSON的对象格式的字符串 [

  • 详解java生成json字符串的方法

    例1:将map对象添加一次元素(包括字符串对.数组),转换成json对象一次. 代码: package com.json; //这是使用org.json的程序: import java.util.HashMap; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; public class jsontest { public static void main(String[] args)

  • Java Web程序实现返回JSON字符串的方法总结

    基础铺垫 在java中,关于json的lib有很多,比如jackjson.fastjson.gson等等,本人都用过,但是对于我等只需要让java对象返回json字符串即可的程序员来说,还是显得过于繁重.而且有些功能定制性很差,比如一个java对象的属性为空时,这些组件都不会输出,于是本人在页面循环遍历列表对象时,总是得判断此属性是否为undefined,这一点让本人很不满意.所以决定花点时间研究下到底是怎么回事. 但经过一上午的细看,发现不管是fastjson还是gson都代码都写得相当的复杂

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

    java遍历json字符串,取得相应KV值时,各种麻烦,比如将json中的list取出来转为JSONArray,再将list中的object转化为map,再取值(之前的做法),仙子啊通过阿里的fastjson,可以很方便的直接将str转化为JSONArray,再将里面的object强转为JSONObject,然后再通过obj.getInteger("key")和obj.getString("key")等取值. JSONArray json = (JSONArray)

  • js动态添加表格逐行添加、删除、遍历取值的实例代码

    关于js对表格进行逐行添加,今天抽空整理了一下:新建一个html文件(没有编辑器的可以新建一个demo.txt文件,然后改后缀名为demo.html),把下面代码全部贴进去即可. 功能包括:表格添加一行,表格删除一行,表格遍历取值等. 点击说明:点击添加按钮,则表格添加一行,可进行录入,删除按钮,可删除当前行,其他行不影响.删除或者添加,每行的的编号都会自动变化,套餐和价格是<input/>,内容是 <textarea></textarea>,点击保存按钮的时候,遍历表

  • java判断中文字符串长度的简单实例

    话不多说,上代码: /** * 获取字符串的长度,如果有中文,则每个中文字符计为2位 * @param value 指定的字符串 * @return 字符串的长度 */ public static int length(String value) { int valueLength = 0; String chinese = "[\u0391-\uFFE5]"; /* 获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1 */ for (int i = 0; i <

  • dataframe设置两个条件取值的实例

    如下所示: >>> import pandas as pd >>> import numpy as np >>> from pandas import Series, DataFrame >>> df = DataFrame({'name':['a','a','b','b'],'classes':[1,2,3,4],'price':[11,22,33,44]}) >>> df classes name price 0

  • innodb_flush_method取值方法(实例讲解)

    innodb_flush_method的几个典型取值 fsync: InnoDB uses the fsync() system call to flush both the data and log files. fsync is the default setting. O_DSYNC: InnoDB uses O_SYNC to open and flush the log files, and fsync() to flush the data files. InnoDB does no

  • json字符串对象转换代码实例

    这篇文章主要介绍了json字符串对象转换代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.将字符串转为json对象:JSON.parse(); 2.json对象转字符串:JSON.stringify(); <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>创建json字符串对象</title

  • python 字典 按key值大小 倒序取值的实例

    如下所示: viedoUrl_dict = {1:'hello',2:'python',3:'nihao'} bit_list = sorted(viedoUrl_dict.keys()) bit_list.reverse() for key in bit_list: m3u8_url = viedoUrl_dict[key] print(m3u8_url) 以上这篇python 字典 按key值大小 倒序取值的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们.

随机推荐