首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >JSONArray和JSONObject的转换

JSONArray和JSONObject的转换

作者头像
全栈程序员站长
发布2022-08-15 19:12:15
发布2022-08-15 19:12:15
82400
代码可运行
举报
运行总次数:0
代码可运行

大家好,又见面了,我是你们的朋友全栈君。

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

代码语言:javascript
代码运行次数:0
运行
复制
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转换需要在配合文件中引入这个

代码语言:javascript
代码运行次数:0
运行
复制
<dependency>
    <groupId>net.sf.json-lib</groupId>
    <artifactId>json-lib</artifactId>
    <version>2.4</version>
    <classifier>jdk15</classifier>
</dependency>

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

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/133787.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年5月2,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档