$\begingroup$

In addition to what the other answers have said:

Sometimes you want to serialise things that are not pure data.

For instance, think of a file handle or a connection to a server. Even though the file handle or socket is an int , this number is meaningless the next time the program runs. To properly recreate objects that contain handles to such things, you need to reopen files and recreate connections, and decide what to do if this fails.

Many languages these days support storing anonymous functions within objects, for instance an onBlah() handler in Javascript. This is challenging because such code can contain references to additional pieces of data which in turn need to be serialised. (And then there's the issue of serialising code in a cross-platform way, which is obviously easier for interpreted languages.) Still, even if only a subset of the language can be supported, it can still prove quite useful. Not many serialisation mechanisms attempt to serialise code, but see serialize-javascript.

In cases where you want to serialise an object but it contains something that isn't supported by your serialisation mechanism, you need to rewrite the code in a way that works around this. For instance, you can use enums in place of anonymous functions when there are a finite number of possible functions.

Often you want serialised data to be terse.

If you're sending data over the network or even storing it on disk, it can be important to keep the size small. One of the easiest ways to achieve this is to throw away information that can be rebuilt (for instance, discarding caches, hash tables, and alternate representations of the same data).

Of course, the programmer has to manually select what is to be saved and what is to be discarded, and make sure things are rebuilt when the object is recreated.

Think about the act of saving a game. Objects may contain lots of pointers to graphics data, sound data, and other objects. But most of this stuff can be loaded from the game data files and doesn't need to be stored in a save file. Discarding it can be laborious so little things are often left in. I've hex-edited some save files in my time and discovered data that was clearly redundant, like textual item descriptions.

Sometimes space isn't important but readability is—in which case you might use an ASCII format (possibly JSON or XML) instead.