Skip to content

Dynamic type handling

yfakariya edited this page Oct 6, 2013 · 5 revisions

Dynamic Type Handling

NOTE: This article does NOT describe about dynamic primitive (a.k.a. System.Dynamic.DynamicObject)

Motivation

Some application level protocols specify dynamic typed fields, and you might have to handle dynamic object which generally be represented as dictionary. For example, the API returns type code and type specific values when it successes, or returns error code when it fails. Using MessagePackObject, you can handle such objects.

Samples

// Gets an object which stores dynamic key/value pairs as dictionary object.
Dictionary<MessagePackObject, MessagePackObject> mpoDict = MessagePackSerializer.Create<Dictionary<MessagePackObject, MessagePackObject>>().UnpackFrom(...);

Debug.Assert( dict.Keys.All( v => v.IsTypeOf<String>() );
// Converts dict keys. Note that this line assumes there are no key duplications.
Dictionary<String, MessagePackObject> dict= mpoDict.ToDictionary( kv => (String)kv.Key, kv => kv.Value );

MessaePackObject theValue;
if ( dict.TryGetValue( "error", out theValue ) )
{
     // The data must be error.
     Debug.Assert( theValue.IsTypeOf<String>() );
    // Convert utf-8 binaries to a String object.
     var error = (String) theValue;
     ...
}
else if ( dict.TryGetValue( "results", out theValue ) )
{
    Debug.Assert( theData.IsList );
    // First get values as list.
    IList<MessagePackObject> values = (IList<MessagePackObject>)theValue;
    Debug.Assert( !values.Any() || values.All( v => v.IsTypeOf<Double>()) );
    // Convert values.
    var results = values.Select( v => (double )v );
    ...
}

See Also