Not all projects require Databases. Project I am currently working on doesn't want any DB to be used at all. Rather it should use object serialization to file. This implementation would do lots of objects serialized/deserialized to file开发者_如何学Go. My question here is, what are best practices for object serialization to file ?
It depends heavily on the nature of the data, how likely the classes you will be writing to disk will change, whether you need to store just the class's data or its data and code, and whether it is meant to be human readable.
Object serialization to a file is one technique. Translating your object model to a structured text record (CSV, XML, etc.) is another. Generally, if the objects as referenced in the file must refer to each other, you will need to encode the references to an id number relevant to the file, and have the decoder rebuild the references while the objects are loading.
If you really need to control how the object marshalling to and from storage is done, you can control it in detail through the Externalizable interface. Beware, once you take on all the responsibility, you will need to handle it correctly.
As far as best practices go:
- Create an in-file id for each object instance.
- Encode the object's type in the serialization (this is done for you in default serialization schemes).
- Add an extra field to track the class's revision, as loading "old" objects into newer versions of their classes can be problematic.
- Provide for a layer that can "forward" translate an "old" on disk object of one known revision to the current class revision.
I would have suggested protocol buffers but now I recommend MessagePack
I recommend you to have a look at XStream.
It is a simple library to serialize objects to XML and back.
精彩评论