我试图使用jackson库序列化java动态代理,但出现以下错误:
public interface IPlanet {
String getName();
}
Planet implements IPlanet {
private String name;
public String getName(){return name;}
public String setName(String iName){name = iName;}
}
IPlanet ip = ObjectsUtil.getProxy(IPlanet.class, p);
ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(ip);
//The proxy generation utility is implemented in this way:
/**
* Create new proxy object that give the access only to the method of the specified
* interface.
*
* @param type
* @param obj
* @return
*/
public static <T> T getProxy(Class<T> type, Object obj) {
class ProxyUtil implements InvocationHandler {
Object obj;
public ProxyUtil(Object o) {
obj = o;
}
@Override
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
Object result = null;
result = m.invoke(obj, args);
return result;
}
}
// TODO: The suppress warning is needed cause JDK class java.lang.reflect.Proxy
// needs generics
@SuppressWarnings("unchecked")
T proxy = (T) Proxy.newProxyInstance(type.getClassLoader(), new Class[] { type },
new ProxyUtil(obj));
return proxy;
}
我有个例外:
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class $Proxy11 and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.SerializationFeature.FAIL_ON_EMPTY_BEANS) )
问题似乎与hibernate代理对象序列化时发生的问题相同,但我不知道如何以及是否可以使用jacksonhibernate模块来解决问题。
更新:jackson2.0.6版本解决了这个bug
2条答案
按热度按时间tzxcd3kk1#
这可能是jackson中的一个bug——代理类可能被显式地阻止被认为是bean。你可以提交一个bug——如果genson能处理,jackson也应该提交
brgchamk2#
你可以试试根森图书馆http://code.google.com/p/genson/. 我刚刚用它测试了您的代码,它运行良好输出是{“name”:“foo”}
它有一些在其他库中不存在的特性。例如,在没有任何注解的情况下使用带参数的构造函数,或者在运行时对对象应用所谓的beanview(充当模型的视图),可以反序列化为具体类型,等等。。。看看维基http://code.google.com/p/genson/wiki/gettingstarted.