2017-10-09 15 views
0

我正在使用一些遺留代碼,並試圖編寫一個lambda來處理函數。AWS Lambda序列化另一個模塊中的對象

函數看起來象

public Task doTask(Message message) throws Exception { 
    LOG.debug("debug message"); 
    // ... more code 
} 

然而,參數Message定義(與getter和setter)在不同的模塊(和傳過來的依賴性)。因此,我得到的錯誤:

{ 
    "errorMessage": "An error occurred during JSON parsing", 
    "errorType": "java.lang.RuntimeException", 
    "stackTrace": [], 
    "cause": { 
    "errorMessage": "com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.mywebsite.messaging.Message, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information\n at [Source: [email protected]; line: 1, column: 1]", 
    "errorType": "java.io.UncheckedIOException", 
    "stackTrace": [], 
    "cause": { 
     "errorMessage": "Can not construct instance of com.mywebsite.messaging.Message, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information\n at [Source: [email protected]; line: 1, column: 1]", 
     "errorType": "com.fasterxml.jackson.databind.JsonMappingException", 
     "stackTrace": [ 
     "com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)", 
     "com.fasterxml.jackson.databind.DeserializationContext.instantiationException(DeserializationContext.java:892)", 
     "com.fasterxml.jackson.databind.deser.AbstractDeserializer.deserialize(AbstractDeserializer.java:139)", 
     "com.fasterxml.jackson.databind.ObjectReader._bindAndClose(ObjectReader.java:1511)", 
     "com.fasterxml.jackson.databind.ObjectReader.readValue(ObjectReader.java:1102)" 
     ] 
    } 
    } 
} 

如何可能序列化這個對象,甚至不是在我的模塊?

任何和所有的幫助將不勝感激。

謝謝!

回答

0

看起來像com.mywebsite.messaging.Message是一個抽象類/ 接口。在這種情況下:使用@JsonDeserialize將解決問題。

事情是這樣的:

@JsonDeserialize(using = MessageDeserializer.class) 
interface Message { 
} 

@JsonDeserialize(as = MessageImpl.class) 
public class MessageImpl implements Message{ 
//write your implementation 
} 

public class MessageDeserializer extends JsonDeserializer<Message> { 

    @Override 
    public Message deserialize(JsonParser jp, DeserializationContext context) throws IOException { 
     ObjectMapper mapper = (ObjectMapper) jp.getCodec(); 
     ObjectNode root = mapper.readTree(jp); 
     return mapper.readValue(root.toString(), MessageImpl.class); 
    } 
} 

這些鏈接可以幫助您: How to add custom deserializer to interface using jackson http://www.baeldung.com/jackson-exception

希望這有助於!

相關問題