java获取json数组中的值

所需jar包的maven依赖:

    <dependency>
      <groupId>net.sf.json-lib</groupId>
      <artifactId>json-lib</artifactId>
      <version>2.4</version>
      <classifier>jdk15</classifier>
    </dependency>

    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.3</version>
    </dependency>

json例子

一、获取json串的第一级的值。

1.msg为字符串类型的json串,firstKey是需要获取值的名称,如:read、preread
/**
     * Json一级查询
     * @param msg  json转换成字符串类型
     * @param firstKey    要获取值的名称
     * @return
     */
    public static String result(String msg,String firstKey){
        String result;
        try {
            JsonParser jsonParser=new JsonParser();
            JsonObject jsonObject=jsonParser.parse(msg).getAsJsonObject();
            result=jsonObject.get(firstKey).getAsString();

        }catch (Exception e){
            //e.printStackTrace();
            result="-";
        }
        return result;
    }

二、获取json串的第二级的值,如:current、num_procs的值

2.msg为字符串类型的json串,firstKey是需要获取值的名称,如:pids_stats、cpu_stats,而secondKey如:current、system_cpu_usage
/**
     * json二级查询
     * @param msg
     * @param firstKey
     * @param secondKey
     * @return
     */
    public static String result(String msg,String firstKey,String secondKey){
        String result;
        try {
            JSONObject object= JSONObject.fromObject(msg);
            String ob= object.get(firstKey).toString();

            JsonParser jsonParser=new JsonParser();
            JsonObject jsonObject=jsonParser.parse(ob).getAsJsonObject();
            result=jsonObject.get(secondKey).getAsString();
        }catch (Exception e){
           // e.printStackTrace();
            result="-";
        }
        return result;
    }

三、获取json串的第三级的值,如:total_usage、usage_in_usermode的值

3.msg为字符串类型的json串,firstKey是需要获取值的名称,如:pids_stats、cpu_stats,而secondKey如:cpu_usage、throttling_data,thirdKey如:total_usage、throttled_periods
/**
     * json三级查询
     * @param msg
     * @param firstKey
     * @param secondKey
     * @return
     */
    public static String result(String msg,String firstKey,String secondKey,String thirdKey){
        String result;
        try {
            JSONObject object= JSONObject.fromObject(msg);
            String ob= object.get(firstKey).toString();
            JSONObject jsonObject=JSONObject.fromObject(ob);
            String o=jsonObject.get(secondKey).toString();
            JsonParser jsonParser=new JsonParser();
            JsonObject json=jsonParser.parse(o).getAsJsonObject();
            result=json.get(thirdKey).getAsString();
        }catch (Exception e){
            // e.printStackTrace();
            result="-";
        }
        return result;
    }

猜你喜欢

转载自blog.csdn.net/weixin_42551369/article/details/88896972
今日推荐