Gson json解析工具

json 解析工具 ,谷歌出品

對象轉換字符串

   
   
   
   
HashMap<String,String> hashMap = new HashMap<String, String>();   hashMap.put("id", "1");   hashMap.put("name", "ca");   Gson gson = new Gson();   System.out.println(gson.toJson(hashMap));


在對象轉換字符串的時候,遇到hibernate持久化過來的對象,若是對象屬性包含某個對象時,若是配置了lazy加載的話,hibernate會放置一個臨時代理爲這個對象屬性 ,倒置  Gson在轉換hibernate對象的時候報錯,這裏能夠設置過濾掉對象中的 屬性代理類,自定義設置想要的輸出對象屬性,處理方式以下:

    GsonUtil 類
   
   
   
   
package utils;      import org.apache.commons.lang.ArrayUtils;   import com.google.gson.ExclusionStrategy;   import com.google.gson.FieldAttributes;      public class GsonUtil implements ExclusionStrategy {       private Class<?> target;       private String[] fields;       private Class<?>[] clazz;       private boolean reverse;          public GsonUtil(Class<?> target) {           super();           this.target = target;       }          public boolean shouldSkipClass(Class<?> class1) {           return false;       }          public boolean shouldSkipField(FieldAttributes fieldattributes) {           Class<?> owner = fieldattributes.getDeclaringClass();           Class<?> c = fieldattributes.getDeclaredClass();           String f = fieldattributes.getName();           boolean isSkip = false;                      if (owner == target) {               if (ArrayUtils.contains(fields, f)) {                                  isSkip = true;               }               if (ArrayUtils.contains(clazz, c)) {                                isSkip = true;               }               if (reverse) {                   isSkip = !isSkip;               }           }              return isSkip;       }          public void setFields(String[] fields) {           this.fields = fields;       }          public void setClazz(Class<?>[] clazz) {           this.clazz = clazz;       }          public void setReverse(boolean reverse) {           this.reverse = reverse;       }   } 



    代碼調用

   
   
   
   
Dog dog = new Dog();   dog.setAge("12");   dog.setId("454");   dog.setName("白狗");   GsonUtil gsonUtil = new GsonUtil(Dog.class);   GsonBuilder builder = new GsonBuilder();   gsonUtil.setFields(new String[]{"id","name"});   gsonUtil.setReverse(true);   builder.addSerializationExclusionStrategy(gsonUtil);   Gson gson = builder.create();   System.out.println(gson.toJson(dog));



字符串轉對象


   
   
   
   
Gson gson = new Gson();   String jsonstr="{\"id\":\"454\",\"name\":\"白狗\"}";   System.out.println(gson.fromJson(jsonstr, Dog.class));//在轉換爲泛型類的時候 需以下轉換list = gson.fromJson(result, new TypeToken<List<Object[]>>() {}.getType())




附件:

gson-2.2.2.jar

附件列表

相關文章
相關標籤/搜索