Google Gson 简单使用

Google Gson 的下载:http://code.google.com/p/google-gson/

一个简单的实例,本人初学,有不对的地方请高人指出,一起学习

User.java

package cn.true123.testgson;

public class User {
private int id;
private String name;

/**
* default construct
*/
User() {
}

User(int id, String name) {
this.id = id;
this.name = name;
}

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;
}

}

生成json字符串

     GsonBuilder gsonBuilder = new GsonBuilder();
     //通过GsonBuilder 的create生成Gson对象
Gson gson = gsonBuilder.create();
List<User> tusers = new ArrayList<User>();
for (int i = 0; i < 5; i++) {
tusers.add(new User(i, "user" + i));
}
     //通过TypeToken活动Type对象
String gsonstr = gson.toJson(tusers, new TypeToken<List<User>>() {
}.getType());
System.out.println(gsonstr);

输出结果:

[{"id":0,"name":"user0"},{"id":1,"name":"user1"},{"id":2,"name":"user2"},{"id":3,"name":"user3"},{"id":4,"name":"user4"}]

下面看看怎么通过Json字符串转换成User对象

第一种情况,转成单个对象

注意字符串不能有"[]"

User user = gson.fromJson("{\"id\":15,\"name\":\"OnlyOne\"}", User.class);
System.out.println("userID = "+user.getId() + ";UserName = " + user.getName());

输出结果

userID = 15;UserName = OnlyOne

第二种情况,转化成对个对象

第二个参数是转成对象的Type类型

List<User> fusers = gson.fromJson(gsonstr, new TypeToken<List<User>>() {
}.getType());
for (User u : fusers) {
System.out.println("userID = "+u.getId() + ";UserName = " + u.getName());
}


输出结果

userID = 0;UserName = user0
userID = 1;UserName = user1
userID = 2;UserName = user2
userID = 3;UserName = user3
userID = 4;UserName = user4

 

其他的自己看API吧,http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/index.html

 



 




posted @ 2012-03-19 10:39  feimeng0530  阅读(1167)  评论(0编辑  收藏  举报