![](/img/trans.png)
[英]XML Serialization Issue - Object Will Serialize But Not Deserialize Some Properties
[英]Object with some fix properties and some dynamic properties serialization
我有一個包含一些固定屬性的類,並且我還必須支持在運行時確定的動態屬性。
我的問題是我想將該類序列化為json
,所以我決定從Dictionary
繼承。
public class TestClass : Dictionary<string,object>
{
public string StudentName { get; set; }
public string StudentCity { get; set; }
}
我這樣使用它:
static void Main(string[] args)
{
TestClass test = new TestClass();
test.StudentCity = "World";
test.StudentName = "Hello";
test.Add("OtherProp", "Value1");
string data = JsonConvert.SerializeObject(test);
Console.WriteLine(data);
Console.ReadLine();
}
我的輸出是這樣的:
{"OtherProp":"Value1"}
但我期望這樣:
{"OtherProp":"Value1", "StudentName":"Hello" , "StudentCity":"World"}
如您所見,它不會序列化StudentName
和StudentCity
。
我知道一種解決方案是使用Reflection來向字典添加Fix屬性,或者使用Json.net使其自身為JObject.FromObject,但是要做到這一點,我必須進行操作。
我還嘗試使用JObject
屬性裝飾TestClass
,但它不會產生所需的輸出。
我不想為此編寫自定義轉換器,因為這將是我的最后選擇。
任何幫助或建議,將不勝感激。
你應該像這樣實現你的課程
public class TestClass : Dictionary<string, object>
{
public string StudentName
{
get { return this["StudentName"] as string; }
set { this["StudentName"] = value; }
}
public string StudentCity
{
get { return this["StudentCity"] as string; }
set { this["StudentCity"] = value; }
}
}
這樣,那些固定屬性實際上將像幫助者一樣易於訪問。 注意我在字典中設置值的方式。 這樣,如果密鑰不存在,則會創建該密鑰,並為該密鑰分配值,否則將更新該值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.