首頁技術(shù)文章正文

Android+物聯(lián)網(wǎng)培訓實戰(zhàn)教程之使用google-gson處理json格式數(shù)據(jù)

更新時間:2017-07-02 來源:黑馬程序員Android+物聯(lián)網(wǎng)培訓學院 瀏覽量:



 
一、概述:
     Gson是Google提供的一個Java庫,它可以用來將Java對象轉(zhuǎn)換為JSON字符串。還可以用于將JSON字符串轉(zhuǎn)換為等效的Java對象。另外,其另一個特點是支持java的泛型集合和json字符串之間的轉(zhuǎn)換。
 
二、API介紹
     1.google-gson的Gson對象的創(chuàng)建方法:
          Gson gson=new Gson();
          Gson gson=new GsonBuilder().create();
 
     2.google-gson的使用非常簡單,其提供的toJson()和fromJson()方法用于Java對象和JSON格式字符串的相互轉(zhuǎn)換。
          toJson():用于把java對象轉(zhuǎn)換為json格式字符串
          fromJson():用于把json格式字符串轉(zhuǎn)換為java對象
 
 
三、實例
 
實體類User:
 
public class User {
         private String name;
         private int age;
         private String address;
         public String getName() {
                   return name;
         }
         public void setName(String name) {
                   this.name = name;
         }
         public int getAge() {
                   return age;
         }
         public void setAge(int age) {
                   this.age = age;
         }
         public String getAddress() {
                   return address;
         }
         public void setAddress(String address) {
                   this.address = address;
         }
         public User(String name, int age, String address) {
                   super();
                   this.name = name;
                   this.age = age;
                   this.address = address;
         }
         @Override
         public String toString() {
                   return "User [name=" + name + ", age=" + age + ", address=" + address
                                     + "]";
         }
        
        
 
}
 
 
 
 
 
使用google-gson的代碼片段如下:
 
 
    //0. 初始化json、User數(shù)組、List<User>、Map<String,User>、google-gson對象等數(shù)據(jù):
 
                //構(gòu)建json格式的字符串
                String jsonString="{'name':'tom','age':23,'address':'北京'}"; 
                  
                   User u1=new User("艾迪森", 25, "北京");
                   User u2=new User("安迪", 23, "南京");
                   User u3=new User("托馬斯", 21, "上海");
                   User u4=new User("愛麗絲", 22, "鄭州");
                  
                   User []us={u1,u2,u3,u4};
                  
                   List<User> users=new ArrayList<User>();
                   users.add(u1);
                   users.add(u2);
                   users.add(u3);
                   users.add(u4);
                  
                  
                   Map<String,User> maps=new HashMap<String, User>();
                   maps.put("1001", u1);
                   maps.put("1002", u2);
                   maps.put("1003", u3);
                   maps.put("1004", u4);
                  
     
                  
                   //創(chuàng)建gson對象
                   Gson g=new GsonBuilder().create();
   
 
    //1.json(對象)字符串和java對象間的相互轉(zhuǎn)換
 
                  
                   //把json格式的數(shù)據(jù)轉(zhuǎn)換為java對象
                   User u=g.fromJson(jsonString,User.class);
                   System.out.println(u);
 
       //輸出結(jié)果:User [name=tom, age=23, address=北京]
 
                  
                   //java對象的信息轉(zhuǎn)換為json字符串
                   jsonString=g.toJson(u);
                   System.out.println(jsonString);
 
      //輸出結(jié)果:{"name":"tom","age":23,"address":"北京"}
    
                  
    //2.json(數(shù)組)字符串和java對象數(shù)組間的相互轉(zhuǎn)換
                  
                   //把java的數(shù)組轉(zhuǎn)為json格式字符串
                   jsonString=g.toJson(us);
                   System.out.println(jsonString);
                  
        //輸出結(jié)果:
                   [
                      {"name":"艾迪森","age":25,"address":"北京"},
                      {"name":"安迪","age":23,"address":"南京"},
                      {"name":"托馬斯","age":21,"address":"上海"},
                      {"name":"愛麗絲","age":22,"address":"鄭州"}
                   ]
 
         
                   us=null;
                   //把json數(shù)組中的數(shù)據(jù)轉(zhuǎn)為java數(shù)組對象
                   us=g.fromJson(jsonString, User[].class);
                   for(User uu:us){
                            System.out.println(uu);
                   }
 
         //輸出結(jié)果:
              User [name=艾迪森, age=25, address=北京]
               User [name=安迪, age=23, address=南京]
              User [name=托馬斯, age=21, address=上海]
              User [name=愛麗絲, age=22, address=鄭州]
 
 
                  
    //3.json(數(shù)組)字符串和java泛型集合對象List間的相互轉(zhuǎn)換
                  
                   //把list中的元素轉(zhuǎn)為json格式數(shù)組
                   jsonString=g.toJson(users);
                   System.out.println(jsonString);
   
        //輸出結(jié)果:同數(shù)組
                   [
                      {"name":"艾迪森","age":25,"address":"北京"},
                      {"name":"安迪","age":23,"address":"南京"},
                      {"name":"托馬斯","age":21,"address":"上海"},
                      {"name":"愛麗絲","age":22,"address":"鄭州"}
                   ]
           
                  
                   users.clear();
                   //把json數(shù)組中的數(shù)據(jù)轉(zhuǎn)為java集合對象list
                   TypeToken<List<User>> typeToken=new TypeToken<List<User>>(){};
                   Type type=typeToken.getType();
 
                   //如果使用了泛型集合就要使用type,指定泛型的具體類型。
                   users=g.fromJson(jsonString,type);
                   for(User uu:users){
                            System.out.println(uu);
                   }
 
        //輸出結(jié)果:同數(shù)組
                    User [name=艾迪森, age=25, address=北京]
                     User [name=安迪, age=23, address=南京]
                    User [name=托馬斯, age=21, address=上海]
                    User [name=愛麗絲, age=22, address=鄭州]    
 
                  
    //4.json(對象)字符串和java泛型集合對象Map間的相互轉(zhuǎn)換 
                  
                   //把map的中的數(shù)據(jù)轉(zhuǎn)為json格式
                   jsonString=g.toJson(maps);
                   System.out.println(jsonString);
        
        //輸出結(jié)果:
                {  
                  "1003":{"name":"托馬斯","age":21,"address":"上海"},
                  "1004":{"name":"愛麗絲","age":22,"address":"鄭州"},
                  "1001":{"name":"艾迪森","age":25,"address":"北京"},
                  "1002":{"name":"安迪","age":23,"address":"南京"}
                 }
                                    
                   maps.clear();
                   //把json數(shù)組中的數(shù)據(jù)轉(zhuǎn)為java集合對象
                   TypeToken<Map<String,User>> typeTokenMap=new TypeToken<Map<String,User>>(){};
                   Type typeMap=typeTokenMap.getType();
                   //如果使用了泛型集合就要使用type,指定泛型的具體類型。
                   maps=g.fromJson(jsonString,typeMap);
                   for(Map.Entry<String, User> uu:maps.entrySet()){
                            System.out.println(uu.getValue());
                   }
 
 
        //輸出結(jié)果:
                   User [name=托馬斯, age=21, address=上海]
                   User [name=愛麗絲, age=22, address=鄭州]
                    User [name=艾迪森, age=25, address=北京]
                   User [name=安迪, age=23, address=南京]
           

本文版權(quán)歸黑馬程序員Android+物聯(lián)網(wǎng)培訓學院所有,歡迎轉(zhuǎn)載,轉(zhuǎn)載請注明作者出處。謝謝!
作者:黑馬程序員Android+物聯(lián)網(wǎng)培訓學院
首發(fā):http://android.itheima.com
分享到:
在線咨詢 我要報名
和我們在線交談!