Json使用Jackson库序列化JDK动态代理

car*_*ini 6 java json dynamic-proxy jackson

我正在尝试使用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;
}
Run Code Online (Sandbox Code Playgroud)

我得到这个例外:

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) )
Run Code Online (Sandbox Code Playgroud)

问题似乎与hibernate代理对象序列化时发生的情况相同,但我不知道如何以及如何使用Jackson-hibernate-module来解决我的问题.

更新:BUG是从Jackson 2.0.6版本中解决的

eug*_*gen 2

您可以尝试 Genson 库http://code.google.com/p/genson/。我刚刚用它测试了你的代码,它工作正常,输出是 {"name":"foo"}

Planet p = new Planet();
p.setName("foo");
IPlanet ip = getProxy(IPlanet.class, p);
Genson genson = new Genson();
System.out.println(genson.serialize(ip));
Run Code Online (Sandbox Code Playgroud)

它有一些其他库中不存在的好功能。例如使用带参数的构造函数而不带任何注释,或者在运行时在对象上应用所谓的 BeanView(充当模型的视图),可以反序列化为具体类型等等......看看 wiki http: // /code.google.com/p/genson/wiki/GettingStarted