Robust way to save/load objects with dependencies?
<p>I'm writing an Android game in Java and I need a robust way to save and load application state quickly. The question seems to apply to most OO languages.</p>

<p>To understand what I need to save: I'm using a Strategy pattern to control my game entities. The idea is I have a very general Entity class which e.g. stores the location of a bullet/player/enemy and I then attach a Behaviour class that tells the entity how to act:</p>

<pre><code>class Entiy { float x; float y; Behavior b; }

abstract class Behavior { void update(Entity e); {}

// Move about at a constant speed
class MoveBehavior extends Behavior { float speed; void update ... }

// Chase after another entity
class ChaseBehavior extends Behavior { Entity target; void update ... }

// Perform two behaviours in sequence
class CombineBehavior extends Behavior { Behaviour a, b; void update ... }
</code></pre>

<p>Essentially, Entity objects are easy to save but Behaviour objects can have a semi-complex graph of dependencies between other Entity objects and other Behaviour objects. I also have cases where a Behaviour object is shared between entities. I'm willing to change my design to make saving/loading state easier, but the above design works really well for structuring the game.</p>

<p>Anyway, the options I've considered are:</p>

<ul>
<li><p>Use Java serialization. This is meant to be really slow in Android (I'll profile it sometime). I'm worried about robustness when changes are made between versions however.</p></li>
<li><p>Use something like JSON or XML. I'm not sure how I would cope with storing the dependencies between objects however. Would I have to give each object a unique ID and then use these IDs on loading to link the right objects together? I thought I could e.g. change the ChaseBehaviour to store a ID to an entity, instead of a reference, that would be used to look up the Entity before performing the behaviour. </p></li>
</ul>

<p>I'd rather avoid having to write lots of loading/saving code myself as I find it really easy to make mistakes (e.g. forgetting to save something, reading things out in the wrong order).</p>

<p>Can anyone give me any tips on good formats to save to or class designs that make saving state easier?</p>
