簡體   English   中英

Json使用Jackson庫序列化JDK動態代理

[英]Json Serializing JDK Dynamic Proxy with Jackson library

我正在嘗試使用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代理對象序列化時發生的情況相同,但我不知道如何以及如何使用Jackson-hibernate-module來解決我的問題。

更新 :BUG是從Jackson 2.0.6版本中解決的

您可以嘗試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));

它有一些很好的功能,在其他庫房中不存在。 比如在沒有任何注釋的情況下使用帶有參數的構造函數或者在運行時在對象上應用所謂的BeanView(作為模型的視圖),可以反序列化為具體類型,等等...看看wiki http:/ /code.google.com/p/genson/wiki/GettingStarted

這可能是傑克遜的一個錯誤 - 代理類可能被明確阻止被視為bean。 你可以提出一個錯誤 - 如果Genson可以處理它,傑克遜也應該。 :-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM