Skip to content

Writing An Object

hotchaipro edited this page Oct 24, 2018 · 1 revision

The IObjectWriter interface supports writing (or serializing) objects in a format that can be later read by IObjectReader.

IObjectWriter supports a range of primitive value types as well as arrays (including multidimensional arrays) and nested objects.

Writing an object

To write a null object, call WriteNullValue:

if (obj == null) { writer.WriteNullValue(); }

Otherwise, call WriteStartObject:

writer.WriteStartObject();

Write each member key and value using WriteStartMember, WriteValue, and WriteEndMember:

writer.WriteStartMember(1);
writer.WriteValue("Hello, World!");
writer.WriteEndMember();

Note that WriteStartMember requires an integer key value in order to optimize the size of the serialized data structures. However, it is possible to create a simple mapping of strings to and from these integer values using the .NET Dictionary class should you wish.

Call WriteEndObject:

writer.WriteEndObject();

And finally, call Flush to clear out any buffers and write them to the output:

writer.Flush();

Here's the complete example:

if (obj == null)
{
    writer.WriteNullValue();
}
else
{
    writer.WriteStartObject();

    writer.WriteStartMember(1);
    writer.WriteValue("Hello, World!");
    writer.WriteEndMember();

    writer.WriteEndObject();
}

writer.Flush();

Writing primitive values

The WriteValue method supports the following primitive value types:

  • Boolean
  • Int32 / UInt32
  • Int64 / UInt64
  • Single
  • Double
  • Byte[]
  • String

Writing arrays

Arrays can contain primitive value types as well as nested objects or arrays.

Note that an array cannot be a top-level object. This ensures that all serialized objects can be extended with new members without breaking backward compatibility.

To write a null array, call WriteNullValue:

if (array == null) { writer.WriteNullValue(); }

Otherwise, call WriteStartArray:

writer.WriteStartArray();

Write each array value using WriteValue:

foreach (var value in array)
{
    writer.WriteValue(value);
}

And finally, call WriteEndArray:

writer.WriteEndArray();

Here's the entire example:

if (array == null)
{
    writer.WriteNullValue();
}
else
{
    writer.WriteStartArray();

    foreach (var value in array)
    {
        writer.WriteValue(value);
    }

    writer.WriteEndArray();
}

Writing nested objects

IObjectWriter supports arbitrarily nested objects both as member values and array values.

Just use the same pattern as writing a top-level object.

That's it!

Clone this wiki locally