栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java 解析Json数据

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java 解析Json数据

一、普通json格式

如:{“name”:“乔治”,“id”:1}

   private void getObject(String json){
        JSonObject jsonObject = JSON.parseObject(json);
        String id = jsonObject.getString("id");
        String s = jsonObject.getString("name");
        System.out.println(id);
        System.out.println(s);
    }

二、json中包含对象

如:{“user”:{“id”:2,“name”:“王”}}

      private void getObject2(String json){
	        JSonObject jsonObject = JSON.parseObject(json);
	        JSonObject user = jsonObject.getJSonObject("user");
	        Integer id = user.getInteger("id");
	        String name = user.getString("name");
	        System.out.println(id);
	        System.out.println(name);
}

三、json中包含list集合

如:{“list”:[{“id”:3,“name”:“忘3”},{“id”:4,“name”:“忘4”},{“id”:5,“name”:“忘5”},{“id”:6,“name”:“忘6”},{“id”:7,“name”:“忘7”},{“id”:8,“name”:“忘8”},{“id”:9,“name”:“忘9”},{“id”:10,“name”:“忘10”}]}

    private void getArray(String json){
        List list = new ArrayList();
        JSonObject jsonObject = JSON.parseObject(json);
        JSonArray userList = jsonObject.getJSonArray("list");
        for (int i = 0; i < userList.size();i++){
            User2 user2 = new User2();
            JSonObject jsonObject1 = userList.getJSonObject(i);
            System.out.println(jsonObject1.toString());
            user2.setId(jsonObject1.getInteger("id"));
            user2.setName(jsonObject1.getString("name"));
            list.add(user2);
        }
        System.out.println(JSON.toJSON(list));
    }

四、json中包含map集合

如 :{“map”:{“钱”:“14”,“赵”:“12”,“王”:“13”}}

   private  void getMap(String json){
        JSonObject jsonObject = JSON.parseObject(json);
        JSonObject map = jsonObject.getJSonObject("map");
        //获取到所有的key
        Set strings = map.keySet();
        //h获取迭代器
        Iterator iterator = strings.iterator();
        while(iterator.hasNext()){
            String next = iterator.next();
            String string = map.getString(next);
            System.out.println(next+":"+string);
        }
    }

五、json中包含list

如:{“listMap”:[{“钱”:“14”,“赵”:“12”,“王”:“13”},{“钱2”:“14”,“王2”:“13”,“赵2”:“12”}]}

    private void getListMap(String json){

        JSonObject jsonObject = JSON.parseObject(json);
        JSonArray listMap = jsonObject.getJSonArray("listMap");
        for (int i = 0;i strings = jsonObject1.keySet();
            Iterator iterator = strings.iterator();
            while (iterator.hasNext()){
                String next = iterator.next();
                String string = jsonObject1.getString(next);
                System.out.println(next+":"+string);
            }
        }
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/768842.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号