json学习总结

来源:互联网 发布:放苹果问题 c语言 编辑:程序博客网 时间:2024/05/19 04:53

1、JSON和Bean的相互转化

Comment nutch = new Comment("userWbnick", "commentUserRegion","2014-01-02", "userWbName", "commentContent","commentUsernick", "commentUserid", "url", "1");String json = JSON.toJSONString(nutch);//获得JSON字符流System.out.println("json" + json);Comment comm = JSON.parseObject(json, Comment.class);//通过json字符流转变为bean对象System.out.println(comm.toString());
2、通过Map实例化一个JSON

Map<String, Object> jsonMessage = new HashMap<String, Object>();jsonMessage0.put("keywords", news.getKeywords());JSONObject  keywordsJson = new JSONObject(jsonMessage0);
jsonMessage0.put("keywords", news.getKeywords());
添加key-value到map中获得一个JSON
3、JSONArray的使用

JSONArray list = JSONArray.fromObject(responseBodyAsString);

其中responseBodyAsString的风格[{key:value,key1:value},{}],JSONArray的输入输出的格式都是这样的。

News news = JSON.parseObject(list.get(i).toString(), News.class);

list.get(i).toString()获得一个{key:value,key1:value},从而可以实例一个对象。

4、JSON多层数据的处理

String jsonData = "{\"name\":\"lily\",\"nam\":\"lily\",\"age\":23,\"addr\":{\"city\":\"guangzhou\",\"provin\":\"guangdong\"},\"add\":{\"province\":\"guangdong\"}}";        test t=JSON.parseObject(jsonData,test.class);        System.out.println(t.addr.city);
通过构造相应的类提取出其中的数据。

0 0