如何在不实现Serializable接口的情况下序列化/反序列化对象? [英] How to Serialize/Deserialize an object without implementing Serializable interface?

查看:1784
本文介绍了如何在不实现Serializable接口的情况下序列化/反序列化对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果邮件发送到我的收件箱,我会收到一条消息,然后我将内容插入到数据库中。
我有一个org.springframework.integration.core.Message,如下所示:

If a mail is send to my inbox, I recieve a message, and I'm inserting the contents into DB. I have a org.springframework.integration.core.Message something like follows:

public void receive(Message<?> message)
{
    //I am inserting message contents into DB
}

现在如果发生故障,我想要有故障安全恢复机制,我想的是将Message对象序列化为一个文件,然后反序列化并更新到DB。

Now in the event of failure, I wanted to have fail safe recovery mechanism, what I am thinking is to serialize the Message object into a file and later deserialize and update to DB.

问题
1.在这种情况下如何序列化Message对象?
2.除了序列化之外还有其他可以使用的机制吗?

Question 1. In this situation how to serialize the Message object? 2. Other than serialization any other mechanism that can be used?

编辑
之前我还没有进行过序列化,我听说类应该实现Serializable以便使用ObjectOutputStream,在这种情况下我不想创建Message的子类,那么如何将Message序列化为File?

EDIT I have not done Serialization before, I heard like the class should implements Serializable in order to use ObjectOutputStream, in this case I don't want to create a subclass of Message, So how to serialize Message to File?

推荐答案

当然,除了jvm之外,还有许多序列化机制。

Sure, there are many serialization mechanisms apart from the jvm one.


  • XML

  • JSON

  • BSON

  • MessagePack

  • protobufs

  • ...

  • XML
  • JSON
  • BSON
  • MessagePack
  • protobufs
  • ...

其中一些是基于文本,有些是二进制的。都有缺点和优点。基于文本的文本是人类可读的,二进制文件更快,占用的空间更少。

Some of them are text-based, some are binary. All have drawbacks and pluses. Text-based ones are human-readable, binary ones are faster and take up less space.

有一些java库可以处理所有上述格式:JAXB(XML),杰克逊(JSON)等。

There are java libraries that handle all the above formats: JAXB (XML), Jackson (JSON), etc.

这篇关于如何在不实现Serializable接口的情况下序列化/反序列化对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆