我有以下代碼,其中page.Fields
是ExpandoObject
。我遍歷一些用戶定義的屬性並將它們添加到Expando中,將其轉換爲IDictionary<string,string>
以允許我動態添加新的字段名稱/值,但是當我將Fields
屬性設置爲props
的值時,序列化僅在後面給出名稱的空白值爲{}
。爲什麼?使用json.Net序列化ExpandoObject
page.Fields.Foo = "asdf";
var test = JsonConvert.SerializeObject(page); // shows Foo=asdf in the json
// attach all fields to the page object, casting to an IDictionary to be able to add var names
var props = new ExpandoObject() as IDictionary<string, Object>;
foreach (string key in Request.Form.Keys)
{
if (key.StartsWith("Fields."))
{
var fieldName = key.Substring(key.IndexOf(".") + 1);
props.Add(fieldName, Request.Form[key]);
}
}
var test2 = JsonConvert.SerializeObject(props); // blank values of {}
page.Fields = props as ExpandoObject;
// loses the values for the Fields property
test = JsonConvert.SerializeObject(page);
UPDATE南希的詛咒罷工,該Request.Form
值竟然是動態的,所以我不得不.ToString()
它,使之融入預期IDictionary<string,string>
你想要一個動態的,而不是ExpandoObject,而不是「無功道具」使用「動態道具」 – Gusman
Json.NET可以序列化詞典 - 實際上,Json對象是一個JavaScript字典。也許你應該從你的Form.Keys創建並序列化一個'Dictionaty',而不是通過一箇中間對象 –
不,它必須是'var props'而不是'dynamic props',因爲它將它轉換爲IDictionary不是動態的。 –
user3791372