2013-01-31 86 views
4

我正在使用jsonrpc4j並卡住了。我做了一個小例子來說明我的問題:jsonrpc4j:如何將類型信息添加到參數?

抽象類:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME) 
@JsonSubTypes(value = { @JsonSubTypes.Type(value = Walnut.class) }) 
public abstract class Nut { 

} 

具體子類:

public class Walnut extends Nut { 

} 

接口服務:

​​

服務本身:

public class Service implements ServiceInterface { 
    public Nut getNut() { return new Walnut(); } 
    public void setNut(Nut nut) {} 
} 

服務器:

JsonRpcServer rpcServer = new JsonRpcServer(new ObjectMapper(), new Service()); 
StreamServer streamServer = new StreamServer(rpcServer, 50, 1420, 
     50, InetAddress.getByName("127.0.0.1")); 
streamServer.start(); 

客戶:

JsonRpcClient jsonRpcClient = new JsonRpcClient(new ObjectMapper()); 
ServiceInterface remoteService = ProxyUtil.createClientProxy(
     ServiceInterface.class.getClassLoader(), 
     ServiceInterface.class, jsonRpcClient, 
     new Socket(InetAddress.getByName("127.0.0.1"), 1420)); 

如果我叫remoteService.getNut()一切正常,日誌打印:

JSON-PRC Request: {"id":"6064348714687420633","jsonrpc":"2.0","method":"getNut"} 
JSON-PRC Response: {"jsonrpc":"2.0","id":"6064348714687420633", 
     "result":{"@type":"Walnut"}} 

如果我請致電remoteService.setNut(新核桃())服務器拋出一個異常,日誌打印:

JSON-PRC Request {"id":"9194853851254039397","jsonrpc":"2.0", 
     "method":"setNut","params":[{}]} 
Error in JSON-RPC Service com.fasterxml.jackson.databind.JsonMappingException: 
     Unexpected token (END_OBJECT), expected FIELD_NAME: 
     missing property '@type' that is to contain type id (for class Nut) 

參數的類型信息丟失,因爲代理包裝所有的參數到一個對象數組(見我最後question理解爲什麼信息類型在失蹤這個案例)。

我該如何實現所需的序列化?我嘗試啓用默認輸入並通過混合註釋(使用@JsonTypeInfo)Object.class,但都失敗(以下例外)。

啓用默認打字[remoteService.getNut(),誤差在服務器方]:

Exception while handling request 
     com.fasterxml.jackson.databind.JsonMappingException: 
     Unexpected token (START_OBJECT), expected START_ARRAY: 
     need JSON Array to contain As.WRAPPER_ARRAY type information for 
     class com.fasterxml.jackson.databind.JsonNode 

啓用默認打字[remoteService.setNut(新胡桃木()),誤差在客戶端方]:

Exception in thread "main" java.lang.IllegalArgumentException: 
     Unexpected token (START_ARRAY), expected VALUE_STRING: 
     need JSON String that contains type id (for subtype of 
     com.fasterxml.jackson.databind.JsonNode) 

隨着混入物[remoteService.getNut(),服務器端的錯誤]:

Exception while handling request 
     java.lang.IllegalArgumentException: 
     Could not resolve type id 'DefaultErrorResolver$ErrorData' 
     into a subtype of 
     [simple type, class com.fasterxml.jackson.databind.JsonNode] 

與水混合,在[remoteService.setNut(新核桃()),在客戶端錯誤]:

Exception in thread "main" java.lang.ClassCastException: 
     [Ljava.lang.Object; cannot be cast to 
     com.fasterxml.jackson.databind.JsonNode 

任何想法?

+2

如果您只發布代碼的相關部分會更好,但閱讀起來太冗長。 –

+3

這是一個最小工作示例,我不能想到在這種情況下可以省略一行 - 如果您可以指出任何不相關的部分,我可能會改進我的問題。 – nutlike

+0

我認爲完整的代碼是一個很大的好處。我經常在SO和許多論壇上看到關於後續問題的更多代碼的請求,而且我自己處理支持請求經常遵循這種模式。它非常緊湊,它只包括讓問題獨立出來所需的課程。 –

回答

相關問題