利用Google Gson实现JSON字符串和对象之间相互转换

最近一个项目需要用到JSON,需要在JSON字符串和对象之间相互转换,在网上找了些资料,发现google的Gson还是比较不错的。 废话不说,下面是简单的例子: 先上源码:下载(包含jar包) Person实体类 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格式的字符串 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格式的字符串 Gson gs = new Gson(); List persons = new ArrayList(); 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} 代码:         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}] 代码: List jsonListObject = gs.fromJson(listStr, new TypeToken>(){}.getType());//把JSON格式的字符串转为List         for (Person p : jsonListObject) {             System.out.println("把JSON格式的字符串转为List///  "+p.toString());         } 可以看到上面的代码使用了TypeToken,它是Gson提供的数据类型转换器,可以支持各种数据集合类型转换。 Gson的基本使用就这么多,其他请参考官方文档,希望对你们有帮助~~~ --------------------- 本文来自 hsun924 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/hsun924/article/details/8446743?utm_source=copy

猜你喜欢

转载自blog.csdn.net/qq_36838191/article/details/82802971
今日推荐