首页 > 代码库 > google-gson库下的gson的基本使用
google-gson库下的gson的基本使用
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的基本使用