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串的第一级的值。
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;
}
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐



所有评论(0)