Serialization to string

by Patrick Ruckstuhl (modified: 2007 Jun 20)

Since some time Eiffel supports a serialization method completely written in Eiffel. It directly supports serialization to a file or to memory. This example shows how to use this to serialize an arbitrary object structure to a string. The trick is to serialize to memory and look at the serialized byte buffer as a c string which then can be read into an Eiffel string. To deserialize we do the reverse. serialize (a_object: ANY): STRING is -- Serialize `a_object'. require a_object_not_void: a_object /= Void local l_sed_rw: SED_MEMORY_READER_WRITER l_sed_ser: SED_INDEPENDENT_SERIALIZER l_cstring: C_STRING l_cnt: INTEGER do create l_sed_rw.make l_sed_rw.set_for_writing create l_sed_ser.make (l_sed_rw) l_sed_ser.set_root_object (a_object) l_sed_ser.encode -- the `count' gives us the number of bytes -- we have to read and put into the string. l_cnt := l_sed_rw.count create l_cstring.make_by_pointer_and_count (l_sed_rw.buffer.item, l_cnt) Result := l_cstring.substring (1, l_cnt) ensure serialize_not_void: Result /= Void end deserialize (a_string: STRING): ANY is -- Deserialize `a_string'. require a_string_not_void: a_string /= Void local l_sed_rw: SED_MEMORY_READER_WRITER l_sed_ser: SED_INDEPENDENT_DESERIALIZER l_cstring: C_STRING do create l_cstring.make (a_string) create l_sed_rw.make_with_buffer (l_cstring.managed_data) l_sed_rw.set_for_reading create l_sed_ser.make (l_sed_rw) l_sed_ser.decode (True) Result := l_sed_ser.last_decoded_object end

  • Nguyen Van (13 years ago 11/12/2010)

    How to store?

    Hello, Thanks for your serialization solution but i've got a problem with it. I am going to store this string into my database (Mysql) and got rejected due to special characters. Do you know any ways to deal with it?

    • Manu (13 years ago 17/12/2010)

      You may want to encode the string by using only ASCII characters.