【问题标题】:Object with some fix properties and some dynamic properties serialization具有一些修复属性和一些动态属性序列化的对象
【发布时间】: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"}

如您所见,它不会序列化StudentNameStudentCity

我知道一种解决方案是使用反射将 Fix 属性添加到字典中,或者使用 Json.net 它自己的 JObject.FromObject 但要做到这一点,我必须进行操作。

我还尝试使用JObject 属性来装饰TestClass,但它不会产生所需的输出。

我不想为此编写自定义转换器,因为这是我最后的选择。

任何帮助或建议将不胜感激。

【问题讨论】:

  • 您无需进行反射即可将这些属性添加到字典中

标签: c# json.net


【解决方案1】:

你可以像这样实现你的类

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 类型,那么他们只是序列化字典并忽略其他属性。
  • 仅供参考,看看这个答案,它似乎是解决这个问题的另一种方法。 stackoverflow.com/questions/14893614/…
  • 感谢您的建议。实际上我对 Json.net 有点陌生,我很确定答案会在那里,因为我有共同的要求。另外,您的解决方案也很好,很简单,但是当我尝试四处寻找 Json.net 时,我忘了考虑其他方式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-10
  • 1970-01-01
  • 2020-07-11
  • 2017-08-27
  • 2019-07-14
  • 2018-06-22
  • 2012-11-19
相关资源
最近更新 更多