-
Notifications
You must be signed in to change notification settings - Fork 2
Reading An Object
The IObjectReader interface supports reading (or deserializing) objects written by IObjectWriter.
IObjectReader supports a range of primitive value types as well as arrays (including multidimensional arrays) and nested objects.
To read an object, first call ReadStartObject:
if (reader.ReadStartObject())
If it returns false, the object is null.
Otherwise, enumerate the object members using ReadNextMemberKey:
while (reader.MoveToNextMember())
If it returns true, use the MemberKey property to determine which member was read, and read the member value using one of the ReadValue methods:
if (reader.MemberKey == 1) { reader.ReadValueAsInt32(); }
Otherwise, call ReadEndObject:
reader.ReadEndObject();
Note that MoveToNextMember will automatically skip member values that are not explicitly read.
This means that new members can be added (even with deeply nested values) without breaking backward compatibility with older code.
Here's a complete example:
if (reader.ReadStartObject())
{
while (reader.MoveToNextMember())
{
switch (reader.MemberKey)
{
case 1:
int value = reader.ReadValueAsInt32();
break;
}
}
reader.ReadEndObject();
}IObjectReader supports the following primitive value types:
- Boolean (ReadValueAsBoolean())
- Int32 / UInt32 (ReadValueAsInt32/UInt32())
- Int64 / UInt64 (ReadValueAsInt64/UInt64())
- Single (ReadValueAsSingle())
- Double (ReadValueAsDouble())
- Byte[] (ReadValueAsBytes(int quota))
- String (ReadValueAsString(int quota))
Note that a quota must be specified for Byte[] and String types, in order to limit the damage that can be caused by malformed or malicious serializer input (e.g., over a network).
Arrays can contain primitive value types as well as nested objects or arrays.
To read an array, first call ReadStartArray:
if (reader.ReadStartArray())
If it returns false, the array is null.
Otherwise, enumerate the members of the array using MoveToNextArrayValue:
while (reader.MoveToNextArrayValue())
If it returns true, read the array value using one of the ReadValue methods:
reader.ReadValueAsInt32();
Otherwise, call ReadEndArray:
reader.ReadEndArray();
Here's the complete example:
if (reader.ReadStartArray())
{
while (reader.MoveToNextArrayValue())
{
reader.ReadValueAsInt32();
}
reader.ReadEndArray();
}IObjectReader supports arbitrarily nested objects both as member values and array values.
Just use the same pattern as reading a top-level object.
That's it!