Google Gson 封裝

/**
* 測試所使用到的對象
*/
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
相關文章
相關標籤/搜索