无法将扩展DynamicObject的类序列化为JSON字符串。

6
我有一个类foo,它扩展了DynamicObject类。该类还包含一个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);
}

请告诉我是否有遗漏的内容?

1个回答

7
动态对象在JSON.NET中有特殊的处理方式。 DynamicObject拥有GetDynamicMemberNames方法,该方法期望返回该对象的属性名称。 JSON.NET将使用此方法并序列化由其返回名称的属性。 因为您没有覆盖它(或者如果您这样做了-您没有从中返回PropertiesCount属性的名称),所以它们不会被序列化。
您可以使该方法返回您需要的内容,或者更好的方法是,只需使用JsonProperty标记PropertiesCount - 然后它们将被序列化:
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)});
    }
}

哇,太快了。谢谢,问题已经解决了。 - Pranay Deep

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接