首页技术文章正文

Android+物联网培训实战教程之使用google-gson处理json格式数据

更新时间:2017-07-02 来源:黑马程序员Android+物联网培训学院 浏览量:



 
一、概述:
     Gson是Google提供的一个Java库,它可以用来将Java对象转换为JSON字符串。还可以用于将JSON字符串转换为等效的Java对象。另外,其另一个特点是支持java的泛型集合和json字符串之间的转换。
 
二、API介绍
     1.google-gson的Gson对象的创建方法:
          Gson gson=new Gson();
          Gson gson=new GsonBuilder().create();
 
     2.google-gson的使用非常简单,其提供的toJson()和fromJson()方法用于Java对象和JSON格式字符串的相互转换。
          toJson():用于把java对象转换为json格式字符串
          fromJson():用于把json格式字符串转换为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数组、List<User>、Map<String,User>、google-gson对象等数据:
 
                //构建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);
                  
     
                  
                   //创建gson对象
                   Gson g=new GsonBuilder().create();
   
 
    //1.json(对象)字符串和java对象间的相互转换
 
                  
                   //把json格式的数据转换为java对象
                   User u=g.fromJson(jsonString,User.class);
                   System.out.println(u);
 
       //输出结果:User [name=tom, age=23, address=北京]
 
                  
                   //java对象的信息转换为json字符串
                   jsonString=g.toJson(u);
                   System.out.println(jsonString);
 
      //输出结果:{"name":"tom","age":23,"address":"北京"}
    
                  
    //2.json(数组)字符串和java对象数组间的相互转换
                  
                   //把java的数组转为json格式字符串
                   jsonString=g.toJson(us);
                   System.out.println(jsonString);
                  
        //输出结果:
                   [
                      {"name":"艾迪森","age":25,"address":"北京"},
                      {"name":"安迪","age":23,"address":"南京"},
                      {"name":"托马斯","age":21,"address":"上海"},
                      {"name":"爱丽丝","age":22,"address":"郑州"}
                   ]
 
         
                   us=null;
                   //把json数组中的数据转为java数组对象
                   us=g.fromJson(jsonString, User[].class);
                   for(User uu:us){
                            System.out.println(uu);
                   }
 
         //输出结果:
              User [name=艾迪森, age=25, address=北京]
               User [name=安迪, age=23, address=南京]
              User [name=托马斯, age=21, address=上海]
              User [name=爱丽丝, age=22, address=郑州]
 
 
                  
    //3.json(数组)字符串和java泛型集合对象List间的相互转换
                  
                   //把list中的元素转为json格式数组
                   jsonString=g.toJson(users);
                   System.out.println(jsonString);
   
        //输出结果:同数组
                   [
                      {"name":"艾迪森","age":25,"address":"北京"},
                      {"name":"安迪","age":23,"address":"南京"},
                      {"name":"托马斯","age":21,"address":"上海"},
                      {"name":"爱丽丝","age":22,"address":"郑州"}
                   ]
           
                  
                   users.clear();
                   //把json数组中的数据转为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);
                   }
 
        //输出结果:同数组
                    User [name=艾迪森, age=25, address=北京]
                     User [name=安迪, age=23, address=南京]
                    User [name=托马斯, age=21, address=上海]
                    User [name=爱丽丝, age=22, address=郑州]    
 
                  
    //4.json(对象)字符串和java泛型集合对象Map间的相互转换 
                  
                   //把map的中的数据转为json格式
                   jsonString=g.toJson(maps);
                   System.out.println(jsonString);
        
        //输出结果:
                {  
                  "1003":{"name":"托马斯","age":21,"address":"上海"},
                  "1004":{"name":"爱丽丝","age":22,"address":"郑州"},
                  "1001":{"name":"艾迪森","age":25,"address":"北京"},
                  "1002":{"name":"安迪","age":23,"address":"南京"}
                 }
                                    
                   maps.clear();
                   //把json数组中的数据转为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());
                   }
 
 
        //输出结果:
                   User [name=托马斯, age=21, address=上海]
                   User [name=爱丽丝, age=22, address=郑州]
                    User [name=艾迪森, age=25, address=北京]
                   User [name=安迪, age=23, address=南京]
           

本文版权归黑马程序员Android+物联网培训学院所有,欢迎转载,转载请注明作者出处。谢谢!
作者:黑马程序员Android+物联网培训学院
首发:http://android.itheima.com
分享到:
在线咨询 我要报名
和我们在线交谈!