具有一些修复属性和一些动态属性序列化的对象
我有一个类包含一些固定的属性,并且我还必须支持在运行时决定的动态属性。具有一些修复属性和一些动态属性序列化的对象
我的问题是我想将该类序列化到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
。
我知道,一个解决方案是增加修复财产使用反射字典或使用Json.net它的自我JObject.FromObject但要做到这一点,我必须做的操纵。
我也尝试装饰TestClass
与JObject
属性,但它不会产生所需的输出。
我不想为此编写自定义转换器,因为这将是我的最后一个选项。
任何帮助或建议将不胜感激。
您clould实现你的类像这样
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; }
}
}
这样的固定属性实际上是一样的帮手,方便存取。 注意我在字典中设置值的方式。这样,如果密钥不存在,它将被创建,并且分配给该密钥的值将被更新。
我得到了你的观点。但仍然有问题,为什么Json.net不把类的属性当属性从Dictionary继承时序列化。我认为在内部他们试图看看,如果类是Dictionary类型,那么他们只是序列化字典并忽略其他属性。 – dotnetstep
仅供参考这个答案看起来是解决这个问题的另一种方法。 http://stackoverflow.com/questions/14893614/json-net-serialize-dictionary-as-part-of-parent-object –
谢谢你的建议。其实我对Json.net有点新,因为我有共同的要求,我相信答案会在那里。此外,您的解决方案也是很好的一个简单哪个但我尽量到处寻找Json.net我忘了周围想想别的办法。 – dotnetstep
你不需要做反射到这些属性添加到字典中 –