JSON的解析与生成

有关JSON的工具类有很多,都很方便,用过Gson和fastjson,以及最近使用json-lib

一.Object转为Json,生成json

单个对象Object:

Address addr = new Address();
addr.setState("四川");
addr.setCity("成都");

List,Array,Map,Set类型都是同样的方法,简单统一
Gson:

String json = gson.toJson(addr);

FastJson:

String json = JSON.toJSONString(addr);

Json-Lib:

JSONObject json = JSONObject.fromObject(addr);

具体代码:

//bean---->json
        Address addr = new Address();
        addr.setState("四川");
        addr.setCity("成都");

        JSONObject jsonObj = JSONObject.fromObject(addr);
        System.out.println("jsonObj:"+jsonObj);
        //集合-->JSONArray
        Set<Address> set = new HashSet<Address>();
        Address[] addrArray = new Address[2];
        List<Address> list = new ArrayList<Address>();
        Map<String,Object> map=new HashMap<>();
        for(int i=0;i<2;i++){
            Address address = new Address();
            address.setState("四川");
            address.setCity("成都");

            list.add(address);
            addrArray[i]=address;
            set.add(address);
            map.put("add"+i,address);
        }
        JSONArray jsonList = JSONArray.fromObject(list);
        JSONArray jsonArray = JSONArray.fromObject(addrArray);
        JSONArray jsonSet = JSONArray.fromObject(set);
        JSONArray jsonMap = JSONArray.fromObject(map);

结果:

jsonObj:{"city":"成都","state":"四川"}
jsonList:[{"city":"成都","state":"四川"},{"city":"成都","state":"四川"}]
jsonArray:[{"city":"成都","state":"四川"},{"city":"成都","state":"四川"}]
jsonSet:[{"city":"成都","state":"四川"},{"city":"成都","state":"四川"}]
jsonMap:[{"add0":{"city":"成都","state":"四川"},"add1":{"city":"成都","state":"四川"}}]

二.Json转Object,解析json

Json数据:

String jsonStr = "{\"city\":\"成都\",\"state\":\"四川\"}";
String jsonMapStr = "[{\"add0\":{\"city\":\"成都\",\"state\":\"四川\"},\"add1\":{\"city\":\"成都\",\"state\":\"四川\"}}]";
String bigJsonStr = "{\"add0\":{\"city\":\"成都\",\"state\":\"四川\"},\"add1\":{\"city\":\"成都\",\"state\":\"四川\"}}";

Gson:

Gson gson = new Gson;
Address address=gson.fromJson(jsonStr, Address.class);

FastJson:

Address address = JSON.parseObject(jsonStr, Address.class);

Json-Lib:

JSONObject jsonObject = JSONObject.fromObject(jsonStr);
Address address  = (Address) JSONObject.toBean(jsonObject, Address.class);

上面这些是将json装载到自己的实体类里面,json-lib还可以直接使用json,特别是可以直接转发或者存json的时候用,所以我觉得很方便:

JSONObject jsonObject = JSONObject.fromObject(bigJsonStr);
JSONObject add0= (JSONObject) jsonObject.get("add0");
String city= (String) add0.get("city");

结果:

city:成都  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值