Gson 入门笔记

#本文只是一个简单的实例,自己总结所用。如果需要详细的资料,请参考Gson API文档

最近项目里涉及到不同语言之间接口的调用,最后选择Json作为数据格式。在Java,选择了Google的Gson。我也不知道为什么。

先定义测试类:

简单说明:一个Peope类,一个Friend类。Friend继承People

class People{
	public People(){}
	
	String Name;
	String Age;
	String Sex;
	public String getName() {
		return Name;
	}
	public void setName(String name) {
		Name = name;
	}
	public String getAge() {
		return Age;
	}
	public void setAge(String age) {
		Age = age;
	}
	public String getSex() {
		return Sex;
	}
	public void setSex(String sex) {
		Sex = sex;
	}
	
	ArrayList<Friend> friends;
	public ArrayList<Friend> getFriends() {
		return friends;
	}
	public void setFriends(ArrayList<Friend> friends) {
		this.friends = friends;
	}
	
	
}

class Friend extends People{
	Boolean IsGrilFriend;

	public Boolean getIsGrilFriend() {
		return IsGrilFriend;
	}

	public void setIsGrilFriend(Boolean isGrilFriend) {
		IsGrilFriend = isGrilFriend;
	}
}


测试代码:

/**
	 * @param args
	 */
	public static void main(String[] args) {
		People people = new People();
		people.setName("Tom");
		people.setAge("12");
		people.setSex("男");
		
		ArrayList<Friend> _Friends = new ArrayList<Friend>();
		Friend _Friend = new Friend();
		_Friend.setName("Shit");
		_Friend.setAge("11");
		_Friend.setSex("男");
		_Friend.setIsGrilFriend(true);
		_Friends.add(_Friend);
		
		
		people.setFriends(_Friends);
		
		
		Gson gson = new GsonBuilder().create();
		
		
		long Time1 = System.currentTimeMillis();
		String sResultString = gson.toJson(people,people.getClass());
		long Time2 = System.currentTimeMillis();
		
		System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++");
		
		System.out.println(sResultString);
		System.out.println("所使用时间:"+(Time2-Time1));
		
		System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++");
		
		Time1 = System.currentTimeMillis();
		People _Peoples = gson.fromJson(sResultString,people.getClass());
		Time2 = System.currentTimeMillis();
		
		System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++");
		
		System.out.println(_Peoples.friends.size());
		System.out.println("所使用时间:"+(Time2-Time1));
		
		System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++");
		

	}


注:声明Gson对象的两种方式:

		Gson gson = new GsonBuilder().create();
		Gson gson = new Gson();


结果:


+++++++++++++++++++++++++++++++++++++++++++++++++
{"Name":"Tom","Age":"12","Sex":"男","friends":[{"IsGrilFriend":true,"Name":"Shit","Age":"11","Sex":"男"}]}
所使用时间:110
+++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++
1
所使用时间:11
+++++++++++++++++++++++++++++++++++++++++++++++++

好了,也没什么好介绍的,只是入门而已,就写到这吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值