基本的JSONArray与JSONObject操作:
JSONObject jsonObj =new JSONObject(); jsonObj.put("name0", "zhangsan"); jsonObj.put("sex1", "female"); System.out.println(jsonObj); //输出为:{"sex1":"female","name0":"zhangsan"} JSONArray jsonArray =new JSONArray(); jsonArray.add("11"); jsonArray.add("22"); jsonArray.add("33"); System.out.println(jsonArray); //输出为:["11","22","33"]
由java自带的数据结构转换为JSON文本:
1 2 3 4 5 6 7 8 9 10 | JSONArrayString list[]={ "11" , "22" }; JSONArray jsonarray = JSONArray.fromObject(list); jsonarray.add( "33" ); System.out.println(jsonarray); //输出为:["11","22","33"] //可以由Map生成JSONObjectMap map=newHashMap(); map.put( "NO1" , "第一个" ); map.put( "NO2" , "第二个" ); map.put( "NO3" , jsonarray); JSONObject jsonObj = JSONObject.fromObject(map); System.out.println(jsonObj); //输出为:{"NO3":["11","22","33"],"NO2":"第二个","NO1":"第一个"} |
读取JSON文本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | JSONArray jsonarray; JSONObject jsonObj; //读取JSONArray,用下标索引获取String array="[\"11\",\"22\",\"33\"]"; jsonarray = JSONArray.fromObject(array); System.out.println(jsonarray.getString( 1 )); //输出为:22 //读取JSONObjectString object="{\"NO1\":[\"44\",\"55\",\"66\"],\"NO2\":{\"NO1\":\"第一个\"}}"; jsonObj = JSONObject.fromObject(object); System.out.println(jsonObj.get( "NO1" )); //输出为:["44","55","66"] jsonarray = (JSONArray)(jsonObj.get( "NO1" )); System.out.println(jsonarray.getString( 1 )); //输出为:55 //用"键"获取值jsonObj=(JSONObject)jsonObj.get("NO2"); System.out.println(jsonObj); //输出为:{"NO1":"第一个"} |
点击查看更多内容
为 TA 点赞
0 评论
共同学习,写下你的评论
暂无评论
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦