Google Gson的使用方法及JSON 技术对比

  一 、各个JSON技术的简介和优劣
 

1.json-lib

json-lib最开始的也是应用最广泛的json解析工具,json-lib 不好的地方确实是依赖于很多第三方包,
包括commons-beanutils.jar,commons-collections-3.2.jar,commons-lang-2.6.jar,commons-logging-1.1.1.jar,ezmorph-1.0.6.jar,对于复杂类型的转换,json-lib对于json转换成bean还有缺陷,比如一个类里面会出现另一个类的list或者map集合,json-lib从json到bean的转换就会出现问题。json-lib在功能和性能上面都不能满足现在互联网化的需求。

2.开源的Jackson

相比json-lib框架,Jackson所依赖的jar包较少,简单易用并且性能也要相对高些。而且Jackson社区相对比较活跃,更新速度也比较快。Jackson对于复杂类型的json转换bean会出现问题,一些集合Map,List的转换出现问题。Jackson对于复杂类型的bean转换Json,转换的json格式不是标准的Json格式

3.Google的Gson

Gson是目前功能最全的Json解析神器,Gson当初是为因应Google公司内部需求而由Google自行研发而来,
但自从在2008年五月公开发布第一版后已被许多公司或用户应用。Gson的应用主要为toJson与fromJson两个转换函数,无依赖,不需要例外额外的jar,能够直接跑在JDK上。而在使用这种对象转换之前需先创建好对象的类型以及其成员才能成功的将JSON字符串成功转换成相对应的对象。类里面只要有get和set方法,Gson完全可以将复杂类型的json到bean或bean到json的转换,是JSON解析的神器。Gson在功能上面无可挑剔,但是性能上面比FastJson有所差距。

4.阿里巴巴的FastJson

Fastjson是一个Java语言编写的高性能的JSON处理器,由阿里巴巴公司开发。无依赖,不需要例外额外的jar,能够直接跑在JDK上。FastJson在复杂类型的Bean转换Json上会出现一些问题,可能会出现引用的类型,导致Json转换出错,需要制定引用。FastJson采用独创的算法,将parse的速度提升到极致,超过所有json库。

综上4种Json技术的比较,在项目选型的时候可以使用Google的Gson和阿里巴巴的FastJson两种并行使用,如果只是功能要求,没有性能要求,可以使用google的Gson,如果有性能上面的要求可以使用Gson将bean转换json确保数据的正确,使用FastJson将Json转换Bean

 

二、Google的Gson包的使用简介。

Gson类:解析json的最基础的工具类
JsonParser类:解析器来解析JSON到JsonElements的解析树
JsonElement类:一个类代表的JSON元素
JsonObject类:JSON对象类型
JsonArray类:JsonObject数组
TypeToken类:用于创建type,比如泛型List<?>

maven 依赖:

<dependency>
	<groupId>com.google.code.gson</groupId>
	<artifactId>gson</artifactId>
	<version>2.7</version>
</dependency>

三、Gson的使用

首先定义一个类:

package com.test;

import java.util.Date;

public class User {

	private Integer id;
	private int age;
	private String userName;
	private Date birthday;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	public User(Integer id, int age, String userName, Date birthday) {
		super();
		this.id = id;
		this.age = age;
		this.userName = userName;
		this.birthday = birthday;
	}

	public User() {
		super();
	}

}

测试实例:

package com.test;

import java.util.Date;
import java.util.List;
import java.util.Set;

import org.junit.Test;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

public class GsonTest {

	@Test
	public void test1() throws Exception {
		Gson gson = new Gson();
		User user = new User(1, 20, "AA", new Date());

		System.out.println("Bean->转换为JSON字符串:");
		String jsonStr = gson.toJson(user);
		System.out.println(jsonStr);
		System.out.println();
	}

	@Test
	public void test2() throws Exception {
		Gson gson = new Gson();
		String jsonStr = "{\"id\":1,\"age\":20,\"userName\":\"AA\",\"birthday\":\"Nov 14, 2016 4:52:38 PM\"}";
		System.out.println("字符串->转换成Bean对象");
		User user = gson.fromJson(jsonStr, User.class);
		System.out.println(user);
		System.out.println();
	}

	@Test
	public void test3() throws Exception {
		Gson gson = new Gson();
		System.out.println("json转换复杂的bean,比如List,Set,Map:");
		String json = "[{\"id\":\"1\",\"name\":\"Json技术\"},{\"id\":\"2\",\"name\":\"java技术\"}]";
		List list = gson.fromJson(json, new TypeToken<List>() {
		}.getType());
		Set set = gson.fromJson(json, new TypeToken<Set>() {
		}.getType());
		System.out.println();
	}

	@Test
	public void test4() throws Exception {
		Gson gson = new Gson();
		String json = "[{\"id\":\"1\",\"name\":\"Json技术\"},{\"id\":\"2\",\"name\":\"java技术\"}]";
		System.out.println("格式化JSON:");
		gson = new GsonBuilder().setPrettyPrinting().create();
		JsonParser jp = new JsonParser();
		JsonElement je = jp.parse(json);
		json = gson.toJson(je);
		System.out.println(json);
		System.out.println();

	}

	@Test
	public void test5() throws Exception {
		System.out.println("判断字符串是否是json,通过捕捉的异常来判断是否是json");
		String json = "[{\"id\":\"1\",\"name\":\"Json技术\"},{\"id\":\"2\",\"name\":\"java技术\"}]";
		boolean jsonFlag;
		try {
			new JsonParser().parse(json).getAsJsonObject();
			jsonFlag = true;
		} catch (Exception e) {
			jsonFlag = false;
		}
		System.out.println(jsonFlag + ":" + jsonFlag);
		System.out.println();
	}

	@Test
	public void test6() throws Exception {
		System.out.println("从json串中获取属性");
		String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";
		String propertyName = "name";
		String propertyValue = "";
		try {
			JsonParser jsonParser = new JsonParser();
			JsonElement element = jsonParser.parse(json);
			JsonObject jsonObj = element.getAsJsonObject();
			propertyValue = jsonObj.get(propertyName).toString();
			System.out.println("propertyValue:" + propertyValue);
		} catch (Exception e) {
			propertyValue = null;
		}
		System.out.println();
	}

	@Test
	public void test7() throws Exception {
		System.out.println("除去json中的某个属性");
		String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";
		String propertyName = "id";
		JsonParser jsonParser = new JsonParser();
		JsonElement element = jsonParser.parse(json);
		JsonObject jsonObj = element.getAsJsonObject();
		jsonObj.remove(propertyName);
		json = jsonObj.toString();
		System.out.println("json:" + json);
		System.out.println();
	}

	@Test
	public void test8() throws Exception {
		System.out.println("向json中添加属性");
		String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";
		String propertyName = "desc";
		Object propertyValue = "json各种技术的调研";
		JsonParser jsonParser = new JsonParser();
		JsonElement element = jsonParser.parse(json);
		JsonObject jsonObj = element.getAsJsonObject();
		jsonObj.addProperty(propertyName, new Gson().toJson(propertyValue));
		json = jsonObj.toString();
		System.out.println("json:" + json);
		System.out.println();
	}

	@Test
	public void test9() throws Exception {
		System.out.println("修改json中的属性");
		String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";
		String propertyName = "name";
		Object propertyValue = "json各种技术的调研";
		JsonParser jsonParser = new JsonParser();
		JsonElement element = jsonParser.parse(json);
		JsonObject jsonObj = element.getAsJsonObject();
		jsonObj.remove(propertyName);
		jsonObj.addProperty(propertyName, new Gson().toJson(propertyValue));
		json = jsonObj.toString();
		System.out.println("json:" + json);
		System.out.println();
	}

	@Test
	public void test10() throws Exception {
		System.out.println("判断json中是否有属性");
		String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";
		String propertyName = "name";
		boolean isContains = false;
		JsonParser jsonParser = new JsonParser();
		JsonElement element = jsonParser.parse(json);
		JsonObject jsonObj = element.getAsJsonObject();
		isContains = jsonObj.has(propertyName);
		System.out.println("isContains:" + isContains);
		System.out.println();
	}

	@Test
	public void test11() throws Exception {
		System.out.println("json中日期格式的处理");
		GsonBuilder builder = new GsonBuilder();
		builder.setDateFormat("yyyy-MM-dd");
		Gson gson = builder.create();
		User user = new User();
		user.setBirthday(new Date());
		String json = gson.toJson(user);
		System.out.println("json:" + json);
		System.out.println();
	}

	@Test
	public void test12() throws Exception {
		System.out.println("json中对于Html的转义");
		GsonBuilder builder = new GsonBuilder();
		builder.disableHtmlEscaping();
		Gson gson = builder.create();
		System.out.println();
	}
}

运行如下:

判断json中是否有属性
isContains:true

json中日期格式的处理
json:{"age":0,"birthday":"2016-11-14"}

json中对于Html的转义

Bean->转换为JSON字符串:
{"id":1,"age":20,"userName":"AA","birthday":"Nov 14, 2016 5:14:19 PM"}

字符串->转换成Bean对象
User [id=1, age=20, userName=AA, birthday=Mon Nov 14 16:52:38 CST 2016]

json转换复杂的bean,比如List,Set,Map:

格式化JSON:
[
  {
    "id": "1",
    "name": "Json技术"
  },
  {
    "id": "2",
    "name": "java技术"
  }
]

判断字符串是否是json,通过捕捉的异常来判断是否是json
false:false

从json串中获取属性
propertyValue:"Json技术"

除去json中的某个属性
json:{"name":"Json技术"}

向json中添加属性
json:{"id":"1","name":"Json技术","desc":"\"json各种技术的调研\""}

修改json中的属性
json:{"id":"1","name":"\"json各种技术的调研\""}

更多关于GSON的使用方法,请参考【这里面介绍的很详细】:http://www.jianshu.com/p/e740196225a4

转载于:https://my.oschina.net/hapier/blog/787565

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值