2013-02-08 46 views
2

我想用MsgPack(Java)序列化對象。這個對象(除其他外)包含JodaTime的LocalDate,用於表示完美的日期。 MsgPack無法反序列化來自.NET客戶端的消息,因爲它是非標準類型。我可以想到一個非常簡單的方法來實現有效的行爲 - 自定義序列化爲一組整數左右。但是,由於缺少MsgPack的文檔(這對於這樣一個不錯的庫來說是個恥辱),如果有這樣的選項或者沒有(我希望是這樣),我無法找到。MsgPack第三方對象序列化

有人可以給我一個或兩個指針在哪裏看?

回答

2

通過開放源代碼,您可以查看並複製一些代碼段。在這種情況下,我建議你看看設計良好的MessagePack和複製模板。

使用MessagePack爲Joda DateTime定製模板的示例。以下模板將DateTime序列化爲Long(Millis from 1970)並將其反序列化爲UTC(DateTimeZone.UTC)。如果你想保持正確的時區也可以很容易地擴展:

public class DateTimeSerializerTemplate extends AbstractTemplate<DateTime> { 
    private DateTimeSerializerTemplate() { 

    } 

    public void write(Packer pk, DateTime target, boolean required) throws IOException { 
     if (target == null) { 
      if (required) { 
       throw new MessageTypeException("Attempted to write null"); 
      } 
      pk.writeNil(); 
      return; 
     } 
     pk.write(target.getMillis()); 
    } 

    public DateTime read(Unpacker u, DateTime to, boolean required) throws IOException { 
     if (!required && u.trySkipNil()) { 
      return null; 
     } 
     return new DateTime(u.readLong(), DateTimeZone.UTC); 
    } 

    static public DateTimeSerializerTemplate getInstance() { 
     return instance; 
    } 

    static final DateTimeSerializerTemplate instance = new DateTimeSerializerTemplate(); 

} 

你們班剛剛註冊上面的模板:

msgpack = new MessagePack(); 
msgpack.register(DateTime.class, DateTimeSerializerTemplate.getInstance()); 
+0

謝謝你的回覆。這是我最終做的,但在這裏忘了我的問題。所以你已經得到了答案! :) –

+0

這個解決方案很好。但是,如果我想獲取當前時區並序列化信息。並閱讀時區信息。我怎麼能實現它? – user1438980

+0

按照解決方案,我根據上面的說明添加一個模板。當進行調試時,寫入操作將進入自定義讀取操作,但從字節數組讀取時,將不會進入自定義讀取方法。爲什麼? – user1438980