码迷,mamicode.com
首页 > 其他好文 > 详细

google-gson库下的gson的基本使用

时间:2016-09-05 19:20:47      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

public class Users {

private String username;
private String password;
private Integer age;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}

public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "{\"username\":\"" + username + "\", \"password\":\"" + password + "\"}";
}
}

 

import java.lang.reflect.Type;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class TestGson {

public static void main(String[] args) {
Users users = new Users();
users.setUsername("zhangsan");
users.setPassword("123123123");
users.setAge(30);

//根据实例 生成json字符串

//创建GSON对象
Gson gson = new Gson();

String json = gson.toJson(users);

System.out.println(json);

String j = "{\"username\":\"lisi\",\"password\":\"lisi123\",\"age\":20}";

Users users1 = gson.fromJson(j, Users.class);
System.out.println(users1.getUsername());

String jes = "[{\"username\":\"lisi\",\"password\":\"lisi123\",\"age\":20},{\"username\":\"lisi1\",\"password\":\"lisi123456\",\"age\":50}]";
//创建复杂类型
Type type = new TypeToken<List<Users>>(){}.getType();
//解析出来
List<Users> us = gson.fromJson(jes,type);

System.out.println(us.size());

for(Users uu:us){
System.out.println(uu.toString());
}

new A(){

@Override
public void say() {
// TODO Auto-generated method stub
super.say();
}

};
}

protected static class A{
public void say(){

}
}
}

google-gson库下的gson的基本使用

标签:

原文地址:http://www.cnblogs.com/hwgok/p/5843096.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!