【发布时间】:2015-08-08 12:33:36
【问题描述】:
我有一个包含一些固定属性的类,此外我还必须支持在运行时确定的动态属性。
我的问题是我想将该类序列化为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。
我知道一种解决方案是使用反射将 Fix 属性添加到字典中,或者使用 Json.net 它自己的 JObject.FromObject 但要做到这一点,我必须进行操作。
我还尝试使用JObject 属性来装饰TestClass,但它不会产生所需的输出。
我不想为此编写自定义转换器,因为这是我最后的选择。
任何帮助或建议将不胜感激。
【问题讨论】:
-
您无需进行反射即可将这些属性添加到字典中