ExpandoObject的空构造函数?

时间:2017-11-06 09:37:08

标签: c# json expandoobject

是否可以动态地向ExpandoObject添加空构造函数?我之所以这样做是因为我使用的是JSON.Net库,似乎需要一个空的构造函数才能将Json对象转换为.NET对象。

我一直关注this guide以了解如何动态地向ExpandoObject添加属性。它还指定了如何添加方法和事件,但我不确定如何添加空构造函数,以便JSON.Net可以使用它来建立.Net对象。

这是我到目前为止编写的代码:

private static void ExpandoTest( Program oProgram )
{
    dynamic oResponse = new ExpandoObject();

    // Add a Constructor
    // ---->>>>>>   HOW TO DO THIS?

    // Dynamically added properties
    AddProperty( oResponse, "success", false );
    AddProperty( oResponse, "nRows", 0 );
    List<Dictionary<string, string>> aResult = GenerateResultsList();
    AddProperty( oResponse, "aResult", aResult );

    // .NET to JSON
    string cExpandoJson = JSONHandler.Serialize( oResponse );

    // JSON to .NET
    // Json.Net needs an empty to constructor of oResponse to do this.

    Debug.WriteLine( "" );
}

// Adds a new property to an ExpandoObject object.
public static void AddProperty( ExpandoObject oObj, string propertyName, object propertyValue )
{
    IDictionary<string, object> oExpandoDict = oObj as IDictionary<string, object>;

    if((oExpandoDict.ContainsKey( propertyName )))
        oExpandoDict[propertyName] = propertyValue;
    else
        oExpandoDict.Add( propertyName, propertyValue );
}


// Converts the .NET object to a JSON string.
public static string Serialize( object oNetObject )
{
    return JsonConvert.SerializeObject( oNetObject );
}

非常感谢。

0 个答案:

没有答案