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

Google Gson 封装

时间:2016-07-29 21:08:53      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

/**
* 测试所使用到的对象
*/
class User{
    
    private String userName;
    
    private String passWord;
    
    public User(String userName, String passWord) {
        this.userName = userName;
        this.passWord = passWord;
    }
    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;
    }
    
    @Override
    public String toString() {
        return "账号为:" + this.userName + "  密码为:" + this.passWord;
    }
}

 



/**
*对象转Json格式字符串:
*/
public static String toJson(Object obj) {
    return new Gson().toJson(obj);
}

User user = new User("张三", "123456");
System.out.println(JsonUtil.toJson(user));

运行结果:
{"userName":"张三","passWord":"123456"}

 


 

/**
* Json格式字符串转单个对象
*/
public static <T> T fromJson(String jsonStr, Type type) {  
      return new Gson().fromJson(jsonStr, type);  
}

String Json = "{\"userName\":\"张三\",\"passWord\":\"123456\"}";
User user = JsonUtil.fromJson(Json, User.class)System.out.println(user);

运行结果:
账号为:张三 密码为:123456

 


 

/**
*如果是多个对象组成的Josn格式字符串
*/
public static <T> List<T> jsonToList(String jsonStr, Class<T[]> type) {
    T[] list = new Gson().fromJson(jsonStr,type);
    return Arrays.asList(list);
}

List<User> list = new ArrayList<User>();
list.add(new User("张三", "123456"));
list.add(new User("李四", "000000"));
String json = JsonUtil.toJson(list);
list = JsonUtil.jsonToList(json, User[].class);
System.out.println(list.get(1));

 运行结果:
账号为:李四  密码为:000000


 

 

 

 

Google Gson 封装

标签:

原文地址:http://www.cnblogs.com/yyjava/p/5719539.html

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