I have a city map with streets that I need to (de-)serialize. Each street is identified by City and id, like this:
private final City city;
private final long id;
The city contains a list of all streets in this city (City.streetList
), so that when saving the model I can just do something like
serializeToFile(modelFile, currentCity);
This works and causes no problems, but now I want to send the street over the network (also using serialization). When I'm serializing the street, obviously the city Object gets serialized, too, so that all streets will get serialized resulting in very large packet sizes, obviously.
I cannot make city
transient, as it is needed to uniquely identify the street. I can also not make City.streetList
transient as I will need the list for my model.
Each city has a unique ID, so something like this should be possible
private void writeObject(ObjectOutputStream out) throws IOException {
if (serializeForNetwork) { // How can I know this here?
out.writeObject(city.getId());
} else {
out.writeObject(city);
}
out.write(id);
}
As stated, I have no idea how the object should know it is being written to network (calling street.setWritingToNetwork(true)
before serializing seems more than ugly) and maybe this is not a good solution anyway?
Any ideas are very much appreciated! :-)