JSONArray和JSONObject的转换

在项目日常开发中常常会遇到JSONArray和JSONObject的转换,很多公司刚入职的小萌新会卡在这里,今天和大家分享一下,有更厉害的大佬也可以指教一下!话不多说上硬菜
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<jsonArray.size();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转换需要在配合文件中引入这个
JSONArray和JSONObject的转换

net.sf.json-lib json-lib 2.4 jdk15

导入包的路径分别是:
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;