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())
附件:
附件列表