0

I've got a class inherited from DynamicObject. It contains all the properties stored in List<MyProperty>:

public class MyObject : DynamicObject
{
    public List<MyProperty> Properties { get; set; }
}
public class MyProperty
{
    public string Name { get; set; }
    public string Value { get; set; }
}

I want to serialize it to JSON using Newtonsoft Json. But after converting it I get an empty object: {}. When I remove inheritance from DynamicObject, I get all my properties serialized as a JSON array. And that's exactly what I need. How can I serialize my class without removing that inheritance?

Waldemar
  • 5,363
  • 3
  • 17
  • 28

2 Answers2

1

I've solved my problem by overriding the GetDynamicMemberNames method:

public override IEnumerable<string> GetDynamicMemberNames()
{
    yield return nameof(this.Properties);
}

Now it serializes just as I need.

Waldemar
  • 5,363
  • 3
  • 17
  • 28
0

Depending on what you want, either or both of these solutions should solve your problem:

public class MyObject : DynamicObject
{
    [JsonProperty("MyList")]
    public List<MyProperty> MyList { get; set; }
}

or

[DataContract]
public class MyObject : DynamicObject
{
    [DataMember]
    public List<MyProperty> MyList { get; set; }
}

From this post.

Community
  • 1
  • 1
Phil Gref
  • 987
  • 8
  • 19