本文实例讲述了Java中Json解析的方法。分享给大家供大家参考,具体如下:
首先准备一个JSON格式的字符串
* String JsonStr = "{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类
*
*
class Person{
private String name,image;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
下面是一个Json解析的程序代码
class MyDay17Xml {
//json字符串
static String JsonStr = "{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'}]}}";
public static void main(String []args) throws JSONException{
List list=jsonStrToList(JsonStr);
System.out.println(list.size());
}
public static List jsonStrToList(String jsonStr) throws JSONException{
List list=new ArrayList();
//通过字符串,获得最外部的json对象
JSonObject jsonObj=new JSonObject(jsonStr);
//通过属性名,获得内部的对象
JSonObject jsonPersons=jsonObj.getJSonObject("object");
//获得json对象组
JSonArray arr=jsonPersons.getJSonArray("persons");
for(int i=0;i
PS:关于json操作,这里再为大家推荐几款比较实用的json在线工具供大家参考使用:
在线JSON代码检验、检验、美化、格式化工具:
http://tools.jb51.net/code/json
JSON在线格式化工具:
http://tools.jb51.net/code/jsonformat
在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson
json代码在线格式化/美化/压缩/编辑/转换工具:
http://tools.jb51.net/code/jsoncodeformat
在线json压缩/转义工具:
http://tools.jb51.net/code/json_yasuo_trans
希望本文所述对大家java程序设计有所帮助。



