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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM