Json工具類 - JsonUtils.java


Json工具類,提供Json與對象之間的轉換。

 

源碼如下:(點擊下載 - JsonUtils.java 、 gson-2.2.4.jar )

 1 import java.lang.reflect.Type;
 2 import java.util.Map;
 3 import com.google.gson.Gson;
 4 import com.google.gson.GsonBuilder;
 5 
 6 /**
 7  * Json工具類
 8  * 
 9  */
10 @SuppressWarnings("unchecked")
11 public class JsonUtils {
12 
13     private static Gson gson;
14 
15     private JsonUtils() {
16     }
17 
18     static {
19         GsonBuilder gb = new GsonBuilder();
20         gb.setDateFormat("yyyy-MM-dd HH:mm:ss");
21         gson = gb.create();
22     }
23 
24     public static final String toJson(Object obj) {
25         return gson.toJson(obj);
26     }
27 
28     public static final <T> T fromJson(final String json, Class<T> clazz) {
29         return gson.fromJson(json, clazz);
30     }
31 
32     public static final <T> T fromJson(final String json, Type t) {
33         return gson.fromJson(json, t);
34     }
35 
36     public static final Map<String, Object> fromJson(final String json) {
37         return fromJson(json, Map.class);
38     }
39 
40 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM