Java中Json解析的方法分析
本文实例讲述了Java中Json解析的方法。分享给大家供大家参考,具体如下:
首先准备一个JSON格式的字符串
*StringJsonStr="{object:{persons:"+ "[{name:'呵呵',image:'http://10.0.159.132:8080/Web/s1.png'},"+ "{name:'哈哈',image:'http://10.0.159.132:8080/Web/s1.png'},"+ "{name:'嘿嘿',image:'http://10.0.159.132:8080/Web/s2.jpg'}]}}"; *然后定义一个Person类 * * classPerson{ privateStringname,image; publicStringgetName(){ returnname; } publicvoidsetName(Stringname){ this.name=name; } publicStringgetImage(){ returnimage; } publicvoidsetImage(Stringimage){ this.image=image; } }
下面是一个Json解析的程序代码
classMyDay17Xml{ //json字符串 staticStringJsonStr="{object:{persons:"+ "[{name:'呵呵',image:'http://10.0.159.132:8080/Web/s1.png'},"+ "{name:'哈哈',image:'http://10.0.159.132:8080/Web/s1.png'},"+ "{name:'嘿嘿',image:'http://10.0.159.132:8080/Web/s2.jpg'}]}}"; publicstaticvoidmain(String[]args)throwsJSONException{ Listlist=jsonStrToList(JsonStr); System.out.println(list.size()); } /** * * * */ publicstaticList jsonStrToList(StringjsonStr)throwsJSONException{ List list=newArrayList (); //通过字符串,获得最外部的json对象 JSONObjectjsonObj=newJSONObject(jsonStr); //通过属性名,获得内部的对象 JSONObjectjsonPersons=jsonObj.getJSONObject("object"); //获得json对象组 JSONArrayarr=jsonPersons.getJSONArray("persons"); for(inti=0;i PS:关于json操作,这里再为大家推荐几款比较实用的json在线工具供大家参考使用:
在线
JSON代码检验、检验、美化、格式化工具: http://tools.jb51.net/code/json
JSON在线格式化工具:
http://tools.jb51.net/code/jsonformat在线XML/
JSON互相转换工具: