【问题标题】:Can't Serialize a class extending DynamicObject into JSON string.无法将扩展 DynamicObject 的类序列化为 JSON 字符串。
【发布时间】:2018-09-16 05:29:13
【问题描述】:

我有扩展 DynamicObject 类的类 foo。 该类还包含一个 Dictionary 类型的属性。

当我尝试使用 Newton.Soft Json 转换器对其进行序列化时。我将“{}”作为空白对象。

以下是我的代码:

public class Foo: DynamicObject
       {
           /// <summary>
           ///     Gets or sets the properties.
           /// </summary>
           /// <value>The properties.</value>
           public Dictionary<string, object> Properties { get; set; } = new Dictionary<string, object>();

           /// <summary>
           ///     Gets the count.
           /// </summary>
           /// <value>The count.</value>
           public int Count => Properties.Keys.Count;

       }

现在我提到了,在对其进行序列化时,我得到了空白对象。 下面是序列化的代码:

public static void Main()
{
  Foo foo= new Foo();
           foo.Properties = new Dictionary<string, object>()
           {
               {"SomeId", 123},
               {"DataType","UnKnonw"},
               {"SomeOtherId", 456},
               {"EmpName", "Pranay Deep"},
              {"EmpId", "789"},
              {"RandomProperty", "576Wow_Omg"}
          };

           //Now serializing..
           string jsonFoo = JsonConvert.SerializeObject(foo);
           //Here jsonFoo = "{}".. why?
           Foo foo2= JsonConvert.DeserializeObject<Foo>(jsonFoo);
}

如果我遗漏了什么,请告诉我?

【问题讨论】:

    标签: c# .net json serialization json.net


    【解决方案1】:

    JSON.NET 以特殊方式处理动态对象。 DynamicObject 具有 GetDynamicMemberNames 方法,该方法应返回该对象的属性名称。 JSON.NET 将使用此方法并使用其返回的名称序列化属性。由于您没有覆盖它(或者如果您这样做了 - 您不会从中返回 PropertiesCount 属性的名称) - 它们没有被序列化。

    您可以让该方法返回您需要的内容,或者更好的是,只需将 PropertiesCount 标记为 JsonProperty - 然后它们无论如何都会被序列化:

    public class Foo : DynamicObject
    {
        [JsonProperty]
        public Dictionary<string, object> Properties { get; set; } = new Dictionary<string, object>();
    
        [JsonProperty]
        public int Count => Properties.Keys.Count;
    }
    
    // also works, NOT recommended
    public class Foo : DynamicObject
    {        
        public Dictionary<string, object> Properties { get; set; } = new Dictionary<string, object>();
    
        public int Count => Properties.Keys.Count;
    
        public override IEnumerable<string> GetDynamicMemberNames() {
            return base.GetDynamicMemberNames().Concat(new[] {nameof(Properties), nameof(Count)});
        }
    }
    

    【讨论】:

    • 哇,真快。谢谢,它解决了这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    • 1970-01-01
    • 2020-04-14
    • 2021-04-27
    相关资源
    最近更新 更多