gson实现字符串与对象的相互转换

最近一个项目需要用到JSON,需要在JSON字符串和对象之间相互转换,在网上找了些资料,发现google的Gson还是比较不错的。

废话不说,下面是简单的例子:

先上源码:下载(包含jar包)


Person实体类

  1. package com.hsun.json;  
  2. /** 
  3.  * Person 实体类 
  4.  * @author hsun 
  5.  * 
  6.  */  
  7. public class Person {  
  8.     private int id;  
  9.     private String name;  
  10.     private int age;  
  11.       
  12.     public int getId() {  
  13.         return id;  
  14.     }  
  15.     public void setId(int id) {  
  16.         this.id = id;  
  17.     }  
  18.     public String getName() {  
  19.         return name;  
  20.     }  
  21.     public void setName(String name) {  
  22.         this.name = name;  
  23.     }  
  24.     public int getAge() {  
  25.         return age;  
  26.     }  
  27.     public void setAge(int age) {  
  28.         this.age = age;  
  29.     }  
  30.       
  31.     @Override  
  32.     public String toString() {  
  33.         return “Person [id=” + id + “, 姓名=” + name + “, 年龄=” + age + “]”;  
  34.     }  
  35. }  
package com.hsun.json;
/**
 * Person 实体类
 * @author hsun
 *
 */
public class Person {
    private int id;
    private String name;
    private int age;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    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;
    }

    @Override
    public String toString() {
        return "Person [id=" + id + ", 姓名=" + name + ", 年龄=" + age + "]";
    }
}
实体很简单,当然Person的字段也可以是List、Set、Map等~~~


把对象转为JSON格式的字符串

  1. Gson gs = new Gson();  
  2.   
  3. Person person = new Person();  
  4. person.setId(1);  
  5. person.setName(”我是酱油”);  
  6. person.setAge(24);  
  7.   
  8. String objectStr = gs.toJson(person);//把对象转为JSON格式的字符串  
  9. System.out.println(”把对象转为JSON格式的字符串///  ”+objectStr);  
       Gson gs = new Gson();

        Person person = new Person();
        person.setId(1);
        person.setName("我是酱油");
        person.setAge(24);

        String objectStr = gs.toJson(person);//把对象转为JSON格式的字符串
        System.out.println("把对象转为JSON格式的字符串///  "+objectStr);

上面的代码重点是Gson对象,它提供了toJason()方法将对象转换成Json字符串,上面代码的objectStr对象值为:

{“id”:1,”name”:”我是酱油”,”age”:24}


把List转为JSON格式的字符串

  1. Gson gs = new Gson();  
  2.   
  3. List<Person> persons = new ArrayList<Person>();  
  4. for (int i = 0; i < 10; i++) {//初始化测试数据  
  5.     Person ps = new Person();  
  6.     ps.setId(i);  
  7.     ps.setName(”我是第”+i+“个”);  
  8.     ps.setAge(i+10);  
  9.     persons.add(ps);  
  10. }  
  11.   
  12. String listStr = gs.toJson(persons);//把List转为JSON格式的字符串  
  13. System.out.println(”把list转为JSON格式的字符串///  ”+listStr);  
        Gson gs = new Gson();

        List<Person> persons = new ArrayList<Person>();
        for (int i = 0; i < 10; i++) {//初始化测试数据
            Person ps = new Person();
            ps.setId(i);
            ps.setName("我是第"+i+"个");
            ps.setAge(i+10);
            persons.add(ps);
        }

        String listStr = gs.toJson(persons);//把List转为JSON格式的字符串
        System.out.println("把list转为JSON格式的字符串///  "+listStr);

上面代码的listStr对象值为:

[{“id”:0,”name”:”我是第0个”,”age”:10},{“id”:1,”name”:”我是第1个”,”age”:11},{“id”:2,”name”:”我是第2个”,”age”:12},{“id”:3,”name”:”我是第3个”,”age”:13},{“id”:4,”name”:”我是第4个”,”age”:14},{“id”:5,”name”:”我是第5个”,”age”:15},{“id”:6,”name”:”我是第6个”,”age”:16},{“id”:7,”name”:”我是第7个”,”age”:17},{“id”:8,”name”:”我是第8个”,”age”:18},{“id”:9,”name”:”我是第9个”,”age”:19}]

很标准的json数据~~~



下面来看看gson的反序列化,Gson提供了fromJson()方法来实现从Json相关对象到Java实体的方法。

我们一般都会碰到两种情况,1:转成单一实体对象  2:转换成对象列表或者其他结构。

先看第一种:

JSON字符串为上面的objectStr:{“id”:1,”name”:”我是酱油”,”age”:24}

代码:

  1.         Person jsonObject = gs.fromJson(objectStr, Person.class);//把JSON字符串转为对象  
  2.         System.out.println(”把JSON字符串转为对象///  ”+jsonObject.toString());  
        Person jsonObject = gs.fromJson(objectStr, Person.class);//把JSON字符串转为对象
        System.out.println("把JSON字符串转为对象///  "+jsonObject.toString());
提供两个参数,分别是json字符串以及需要转换对象的类型。


第二种,转换成列表类型:

JSON字符串为上面的listStr:[{“id”:0,”name”:”我是第0个”,”age”:10},{“id”:1,”name”:”我是第1个”,”age”:11},{“id”:2,”name”:”我是第2个”,”age”:12},{“id”:3,”name”:”我是第3个”,”age”:13},{“id”:4,”name”:”我是第4个”,”age”:14},{“id”:5,”name”:”我是第5个”,”age”:15},{“id”:6,”name”:”我是第6个”,”age”:16},{“id”:7,”name”:”我是第7个”,”age”:17},{“id”:8,”name”:”我是第8个”,”age”:18},{“id”:9,”name”:”我是第9个”,”age”:19}]

代码:

  1.         List<Person> jsonListObject = gs.fromJson(listStr, new TypeToken<List<Person>>(){}.getType());//把JSON格式的字符串转为List  
  2.         for (Person p : jsonListObject) {  
  3.             System.out.println(”把JSON格式的字符串转为List///  ”+p.toString());  
  4.         }  
        List<Person> jsonListObject = gs.fromJson(listStr, new TypeToken<List<Person>>(){}.getType());//把JSON格式的字符串转为List
        for (Person p : jsonListObject) {
            System.out.println("把JSON格式的字符串转为List///  "+p.toString());
        }
可以看到上面的代码使用了TypeToken,它是Gson提供的数据类型转换器,可以支持各种数据集合类型转换。


Gson的基本使用就这么多,其他请参考官方文档,希望对你们有帮助~~~




  • 5
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值