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类
*
*

 

 1 class Person{
 2     private String name,image;
 3 
 4     public String getName() {
 5         return name;
 6     }
 7 
 8     public void setName(String name) {
 9         this.name = name;
10     }
11 
12     public String getImage() {
13         return image;
14     }
15 
16     public void setImage(String image) {
17         this.image = image;
18     }
19     
20 }

 

下面是一个Json解析的程序代码

 1 class MyDay17Xml {
 2     //json字符串
 3     static String JsonStr = "{object:{persons:" +
 4             "[{name:'呵呵',image:'http://10.0.159.132:8080/Web/s1.png'}," +
 5             "{name:'哈哈',image:'http://10.0.159.132:8080/Web/s1.png'}," +
 6             "{name:'嘿嘿',image:'http://10.0.159.132:8080/Web/s2.jpg'}]}}";
 7 
 8     public static void main(String []args) throws JSONException{
 9         List<Person> list=jsonStrToList(JsonStr);
10         System.out.println(list.size());
11     }
12     /**
13      * 
14      * 
15      * 
16      */
17     public static List<Person> jsonStrToList(String jsonStr) throws JSONException{
18         List<Person> list=new ArrayList<Person>();
19         
20         //通过字符串,获得最外部的json对象
21         JSONObject jsonObj=new JSONObject(jsonStr);
22         //通过属性名,获得内部的对象
23         JSONObject jsonPersons=jsonObj.getJSONObject("object");
24         //获得json对象组
25         JSONArray arr=jsonPersons.getJSONArray("persons");
26         for(int i=0;i<arr.length();i++){
27             //循环对象,并通过getString("属性名");来获得值
28             JSONObject tempJson=arr.getJSONObject(i);
29             Person person=new Person();
30             
31             person.setName(tempJson.getString("name"));
32             person.setImage(tempJson.getString("image"));
33             list.add(person);
34         }
35         return list;
36         
37     }
38     
39 }

 

posted @ 2015-03-07 20:16  张旭小侠  阅读(11550)  评论(0编辑  收藏  举报