FastJson

@Test
    public void ObjectToJson(){
        AreasEntity area = new AreasEntity();
        AreasEntity area1 = new AreasEntity();
        ArrayList<AreasEntity> list = new ArrayList<>();
        area.setId(1L).setCode("ll").setName("工商局");
        area1.setId(1L).setCode("ll").setName("工商局");
        list.add(area);
        list.add(area1);

        String s = JSON.toJSONString(list);
        System.out.println(s);
        //[{"code":"ll","id":1,"name":"工商局"},{"code":"ll","id":1,"name":"工商局"}]
    }
    @Test
    public void MapToJson(){
        AreasEntity area = new AreasEntity();
        AreasEntity area1 = new AreasEntity();

        Map<String, Object> map = new HashMap<>();

        area.setId(1L).setCode("ll").setName("工商局");
        area1.setId(1L).setCode("ll").setName("工商局");
        map.put("area1", area);
        map.put("area2", area1);

        String s = JSON.toJSONString(map);
        System.out.println(s);
        //{"area1":{"code":"ll","id":1,"name":"工商局"},"area2":{"code":"ll","id":1,"name":"工商局"}}

    }

    @Test
    public void JsonToMap(){

//        String s = "\"area1\":{\"code\":\"ll\",\"id\":1,\"name\":\"工商局\"}";

        //字符串转成对象
        String s = "{\"code\":\"ll\",\"id\":1,\"name\":\"工商局\"}";
        AreasEntity areasEntity = JSON.parseObject(s, AreasEntity.class);
        System.out.println(areasEntity);

        //list集合转成对象。静态方法:parseArray
        String s1 = "[{\"code\":\"ll\",\"id\":1,\"name\":\"工商局\"},{\"code\":\"ll\",\"id\":1,\"name\":\"工商局\"}]";
        List<AreasEntity> areasEntities = JSON.parseArray(s1, AreasEntity.class);
        System.out.println(areasEntities);

        //map转成对象   。静态方法:parseObject
        //直接进行反序列化,Map集合是没有泛型的,泛型没有是不安全的集合
        //参数是TypeReference类型
        String s3 = "{\"area1\":{\"code\":\"ll\",\"id\":1,\"name\":\"工商局\"},\"area2\":{\"code\":\"ll\",\"id\":1,\"name\":\"工商局\"}}";
        Map<String, AreasEntity> areasEntityMap = JSON.parseObject(s3, new TypeReference<Map<String, AreasEntity>>() {});
        for (String key : areasEntityMap.keySet()) {
            System.out.println(key+"  " +areasEntityMap.get(key));
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值