There is a child class from DynamicObject, when trying to serialize using JSON.NET, the output is an empty object. What can you do about it? Using ExpandoObject is not an option, since access to the "fields" by key.

public class DataObject : DynamicObject { public IDictionary<string, object> Values; public DataObject(IDictionary<string, object> values) { Values = values; } public override bool TryGetMember(GetMemberBinder binder, out object result) { if (Values.ContainsKey(binder.Name)) { result = Values[binder.Name]; return true; } result = null; return false; } } 

PS An example of how I try to serialize:

 File.WriteAllText("test.json", JsonConvert.SerializeObject(obj)); 

The object is a complex graph of quite impressive size.

    1 answer 1

    Hide the Values ​​field IDictionary<string, object> out and implement the IDictionary<string, object> interface:

     public class DataObject : DynamicObject, IDictionary<string, object> { private readonly IDictionary<string, object> values; public object this[string key] { get { return values[key]; } set { values[key] = value; } } //... 

    Fresh versions of the studio can generate such an implementation automatically.

    Objects that implement IDictionary<,> are handled by the serializer in a special way - exactly as you need.


    If you are only trying to use DynamicObject for serialization, throw it out and use the internal dictionary directly.

    • And you can read more about the latest version of the studio? - VladD
    • @VladD those that are based on Roslyn. VS2015, for example. - Pavel Mayorov
    • And how to make generate? Just through the implement interface? - VladD
    • 3
      @VladD Implement interface through values - Pavel Mayorov