我在我的持久对象上使用 Gson 自定义序列化。同时,我也在使用序列化排除策略。代码如下所示:
public class GsonFactory {
public static Gson build(Type type, final List<String> fieldExclusions,
final List<Class<?>> classExclusions) {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.addSerializationExclusionStrategy(new ExclusionStrategy() {
public boolean shouldSkipField(FieldAttributes f) {
return fieldExclusions == null ? false : fieldExclusions
.contains(f.getName());
}
public boolean shouldSkipClass(Class<?> clazz) {
return classExclusions == null ? false : classExclusions
.contains(clazz);
}
});
// Uncommenting this line will produce error
// gsonBuilder.registerTypeAdapter(type,
// new PersistentObjectJsonSerializer());
return gsonBuilder.create();
}
}
class PersistentObjectJsonSerializer implements
JsonSerializer<PersistentObject> {
public JsonElement serialize(PersistentObject src, Type typeOfSrc,
JsonSerializationContext context) {
src.setDT_RowId(src.getId());
Gson gson = new Gson();
return gson.toJsonTree(src);
}
}
但是,如果我取消注释gsonBuilder.registerTypeAdapter(type, new PersistentObjectJsonSerializer());
, 在创建时gsonBuilder
将给出以下错误:
java.lang.StackOverflowError
com.google.gson.reflect.TypeToken.equals(TypeToken.java:284)
java.util.HashMap.get(HashMap.java:305)
java.util.Collections$SynchronizedMap.get(Collections.java:1979)
com.google.gson.Gson.getAdapter(Gson.java:337)
com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:55)
com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
com.google.gson.Gson$FutureTypeAdapter.write(Gson.java:883)
我的 PersistentObject java 类:
@MappedSuperclass
public abstract class PersistentObject implements Serializable {
....
@Transient
protected long DT_RowId;
// getters, setters not shown
...
}
这就是我在 GenericHibernateDAO 中调用 GsonFactory.build 的方式:
public abstract class GenericHibernateDAO<T, ID extends Serializable> {
private Class<T> persistentClass;
@SuppressWarnings("unchecked")
public GenericHibernateDAO() {
this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
}
public String listAsJsonResponse(){
...
// testing start
List<Class<?>> classExclusions = new ArrayList<Class<?>>();
classExclusions.add(Role.class);
List<String> fieldExclusions = new ArrayList<String>();
fieldExclusions.add("users");
fieldExclusions.add("password");
Gson gson = GsonFactory.build(persistentClass,fieldExclusions, null);
...
return jsonResponse.toString();
}
}
这里persistentClass
指的是User
类:
@Repository
public class UserDAO extends GenericHibernateDAO<User, Long> {
}
基本上我无法同时使用这两个功能。关于可能导致此问题的任何指针?