Java中的JsonHelper幫助類庫(kù),利用Gson工具實(shí)現(xiàn)Json字符串和Java Bean互轉(zhuǎn)


直接上代碼了,邏輯比較清晰


/** 
 * 使用谷歌Gson實(shí)現(xiàn)Json串和Java Bean互轉(zhuǎn) 
 */  
public class JsonHelper {  
  
    public static String toJson(Object src){  
        return new Gson().toJson(src);  
    }  
  
    public static <T> T fromJson(String json, Class<T> clazz) throws Exception {  
        return new Gson().fromJson(json, clazz);  
    }  
  
    public static <T> List<T> fromJsonArray(String json, Class<T> clazz) throws Exception {  
        List<T> lst =  new ArrayList<T>();  
          
        JsonArray array = new JsonParser().parse(json).getAsJsonArray();  
        for(final JsonElement elem : array){  
            lst.add(new Gson().fromJson(elem, clazz));  
        }  
          
        return lst;  
    }  
}  


原文鏈接:利用Gson工具實(shí)現(xiàn)Json字符串和Java Bean互轉(zhuǎn)