在项目日常开发中常常会遇到JSONArray和JSONObject的转换,很多公司刚入职的小萌新会卡在这里,今天和大家分享一下,有更厉害的大佬也可以指教一下!话不多说上硬菜

public static void main(String[] args) {
String str = "{\"took\":26,\"tid_out\":fale,\"_shards\":{\"total\":160,\"succssful\":10,\"faied\":0},\"hits\":{\"total\":302,\"max_score\":0.0,\"hits\":[]},\"aggations\":{\"agg\":{\"doc_count_error_uper_bound\":0,\"sum_oer_doc_count\":0,\"buets\":[{\"key\":\"http\",\"doc_count\":136},{\"key\":\"web_servers\",\"doc_count\":163},{\"key\":\"dns\",\"doc_count\":235},{\"key\":\"ninx\",\"doc_count\":303},{\"key\":\"nginx服务器\",\"doc_count\":509},{\"key\":\"NLnet bs ND\",\"doc_count\":555}]}}}";
JSONObject jsonObject = JSONObject.fromObject(str);
// System.out.println(jsonObject);
String aggregations= jsonObject.getString("aggregations");
// System.out.println(aggregations);
JSONObject jsonObject1 = JSONObject.fromObject(aggregations);
String agg = jsonObject1.getString("agg");
// System.out.println(agg);
JSONObject jsonObject2 = JSONObject.fromObject(agg);
String buckets =jsonObject2.getString("buckets");
// System.out.println(buckets);
JSONArray jsonArray =JSONArray.fromObject(buckets);
// System.out.println(jsonArray);
for (int i=0;i
JSONObject jsonObject3 = jsonArray.getJSONObject(i);
System.out.println(jsonObject3);
String key = jsonObject3.getString("key");
String doc_count = jsonObject3.getString("doc_count");
System.out.println(key+"------"+doc_count);
}
}
这里的json转换需要在配合文件中引入这个
net.sf.json-lib
json-lib
2.4
jdk15
导入包的路径分别是:
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/hz/128627.html