2012-08-24 29 views
6

我想用傑克遜庫序列化一個Java動態代理,但我得到這個錯誤:的Json序列化JDK動態代理與傑克遜庫

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模塊來解決我的問題。

UPDATE: 的BUG是從傑克遜解決了2.0.6發佈

+0

快速問題'p'在這裏 - 它是什麼類型? (行星?)。另外,如果'Planet'正在實施'IPlanet':如果是的話,Proxy有什麼好處? – StaxMan

回答

2

您可以嘗試Genson庫http://code.google.com/p/genson/。 我只是用它測試你的代碼,它工作正常輸出爲{「名」:「富」}

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

它有幾個沒有在其他librairies exisit不錯的功能。 如使用不帶任何註釋的參數的構造函數或在運行時將對象稱爲BeanView應用於對象(可作爲模型的視圖),可以反序列化爲具體類型等...查看wiki http://code.google.com/p/genson/wiki/GettingStarted

+0

非常非常好,我對你的圖書館留下了深刻的印象(因爲看起來你是開發者)!我閱讀文檔並且非常清楚,我想說你已經做得很好,許多註釋也與傑克遜庫類似,這對於最終遷移有幫助。 –

+0

非常感謝,真的很高興你能欣賞我的作品。 – eugen

1

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

+0

好的,謝謝您確認,我會報告問題 –

+0

Jackson數據綁定Github項目報告問題https://github.com/FasterXML/jackson-databind/issues/57 –