如何使 Json.NET 序列化和反序列化也实现 IDictionary<string, object> 的自定义动态类型的已声明属性?

How can I make Json.NET serialize and deserialize declared properties of custom dynamic types that also implement IDictionary<string, object>?

我有一个派生自 DynamicObject 类型的自定义类型。此类型具有在类型中声明的固定属性。因此,除了他们想要的任何动态属性之外,它还允许用户提供一些必需的属性。当我使用 JsonConvert.DeserializeObject<MyType>(json) 方法反序列化此类型的数据时,它不会设置声明的属性,但可以通过动态对象上的对象索引器 属性 访问这些属性。这告诉我它只是将对象视为字典,不会尝试调用声明的 属性 设置器,也不会使用它们来推断 属性 类型信息。

有没有人遇到过这种情况?知道如何指示 JsonConvert class 在反序列化对象数据时考虑声明的属性吗?

我尝试使用自定义 JsonConverter,但这需要我编写复杂的 JSON 读写方法。我希望找到一种方法,通过覆盖 JsonContractResolverJsonConverter 等来注入 属性 合同信息


//#define IMPLEMENT_IDICTIONARY

using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using Newtonsoft.Json;

namespace ConsoleApp1
{
    class Program
    {
        public class MyDynamicObject : DynamicObject
#if IMPLEMENT_IDICTIONARY
            , IDictionary<string, object>
#endif
        {
            private Dictionary<string, object> m_Members;

            public MyDynamicObject()
            {
                this.m_Members = new Dictionary<string, object>();
            }


#if IMPLEMENT_IDICTIONARY
            public int Count { get { return this.m_Members.Count; } }

            public ICollection<string> Keys => this.m_Members.Keys;

            public ICollection<object> Values => this.m_Members.Values;

            bool ICollection<KeyValuePair<string, object>>.IsReadOnly => false;

            /// <summary>
            /// Gets or sets the specified member value.
            /// </summary>
            /// <param name="memberName">Name of the member in question.</param>
            /// <returns>A value for the specified member.</returns>
            public object this[string memberName]
            {
                get
                {
                    object value;
                    if (this.m_Members.TryGetValue(memberName, out value))
                        return value;
                    else
                        return null;
                }
                set => this.m_Members[memberName] = value;
            }
#endif


            public override bool TryGetMember(GetMemberBinder binder, out object result)
            {
                this.m_Members.TryGetValue(binder.Name, out result);
                return true;
            }

            public override bool TrySetMember(SetMemberBinder binder, object value)
            {
                this.m_Members[binder.Name] = value;
                return true;
            }

            public override bool TryDeleteMember(DeleteMemberBinder binder)
            {
                return this.m_Members.Remove(binder.Name);
            }

            public override IEnumerable<string> GetDynamicMemberNames()
            {
                var names = base.GetDynamicMemberNames();
                return this.m_Members.Keys;
            }

#if IMPLEMENT_IDICTIONARY
            bool IDictionary<string, object>.ContainsKey(string memberName)
            {
                return this.m_Members.ContainsKey(memberName);
            }

            public void Add(string memberName, object value)
            {
                this.m_Members.Add(memberName, value);
            }

            public bool Remove(string memberName)
            {
                return this.m_Members.Remove(memberName);
            }

            public bool TryGetValue(string memberName, out object value)
            {
                return this.m_Members.TryGetValue(memberName, out value);
            }

            public void Clear()
            {
                this.m_Members.Clear();
            }

            void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object> member)
            {
                ((IDictionary<string, object>)this.m_Members).Add(member);
            }

            bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object> member)
            {
                return ((IDictionary<string, object>)this.m_Members).Contains(member);
            }

            public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
            {
                ((IDictionary<string, object>)this.m_Members).CopyTo(array, arrayIndex);
            }

            bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> member)
            {
                return ((IDictionary<string, object>)this.m_Members).Remove(member);
            }

            public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
            {
                return this.m_Members.GetEnumerator();
            }

            IEnumerator IEnumerable.GetEnumerator()
            {
                return this.m_Members.GetEnumerator();
            }
#endif
        }

        public class ProxyInfo
        {
            public string Server;
            public int Port;
        }

        public class CustomDynamicObject : MyDynamicObject
        {
            //[JsonProperty] // NOTE: Cannot do this.
            public string Name { get; set; }

            //[JsonProperty]  // NOTE: Cannot do this.
            public ProxyInfo Proxy { get; set; }
        }


        static void Main(string[] args)
        {
            dynamic obj = new CustomDynamicObject()
            {
                Name = "Test1",
                Proxy = new ProxyInfo() { Server = "http://test.com/",  Port = 10102 }
            };
            obj.Prop1 = "P1";
            obj.Prop2 = 320;

            string json = JsonConvert.SerializeObject(obj);  // Returns: { "Prop1":"P1", "Prop2":320 }

            // ISSUE #1: It did not serialize the declared properties. Only the dynamically added properties are serialized.
            //           Following JSON was expected. It produces correct JSON if I mark the declared properties with
            //           JsonProperty attribute, which I cannot do in all cases.
            string expectedJson = "{ \"Prop1\":\"P1\", \"Prop2\":320, \"Name\":\"Test1\", \"Proxy\":{ \"Server\":\"http://test.com/\", \"Port\":10102 } }";


            CustomDynamicObject deserializedObj = JsonConvert.DeserializeObject<CustomDynamicObject>(expectedJson);

            // ISSUE #2: Deserialization worked in this case, but does not work once I re-introduce the IDictionary interface on my base class.
            //           In that case, it does not populate the declared properties, but simply added all 4 properties to the underlying dictionary.
            //           Neither does it infer the ProxyInfo type when deserializing the Proxy property value and simply bound the JObject token to
            //           the dynamic object.
        }
    }
}

我原以为它会像处理常规类型一样使用反射来解析 属性 及其类型信息。但它似乎只是将对象视为普通字典。

注意:

关于如何使其正常工作有什么建议吗?

我无法分辨 ProxyInfo 中的内容 class。但是,当对 Name 和 Proxy 属性 使用字符串时,反序列化工作正常。请检查以下工作示例:

    class Program
    {
        static void Main(string[] args)
        {
            // NOTE: This is how I load the JSON data into the new type.
            var obj = JsonConvert.DeserializeObject<MyCustomDynamicObject>("{name:'name1', proxy:'string'}");
            var proxy = obj.Proxy;
            var name = obj.Name;
        }
    }

    public class MyDynamicObject : DynamicObject
    {
        // Implements the functionality to store dynamic properties in 
        // dictionary.
        // NOTE: This base class does not have any declared properties.
    }

    // NOTE: This is the actual concrete type that has declared properties
    public class MyCustomDynamicObject : MyDynamicObject
    {
        public string Name { get; set; }
        public string Proxy { get; set; }
    }

你这里有几个问题:

  1. 您需要通过 AlbertK 正确覆盖 DynamicObject.GetDynamicMemberNames() as explained in to 以便 Json.NET 能够序列化您的动态属性。

    (这已在您的问题的编辑版本中修复。)

  2. 声明的属性不会显示,除非您用 [JsonProperty] 明确标记它们(如 this answer to C# How to serialize (JSON, XML) normal properties on a class that inherits from DynamicObject 中所述),但您的类型定义是只读的且无法修改。

    这里的问题好像是JsonSerializerInternalWriter.SerializeDynamic() only serializes declared properties for which JsonProperty.HasMemberAttribute == true。 (我不知道为什么要在那里进行检查,在合同解析器中设置 CanReadIgnored 似乎更有意义。)

  3. 您希望 class 实现 IDictionary<string, object>,但如果您这样做,它会破坏反序列化;声明的属性不再填充,而是添加到字典中。

    这里的问题似乎是 DefaultContractResolver.CreateContract() returns JsonDictionaryContract 而不是 JsonDynamicContract 当传入类型为任何 [=24= 实现 IDictionary<TKey, TValue> 时] 和 TValue.

假设您已解决问题 #1,问题 #2 和 #3 可以通过使用 custom contract resolver 来处理,如下所示:

public class MyContractResolver : DefaultContractResolver
{
    protected override JsonContract CreateContract(Type objectType)
    {
        // Prefer JsonDynamicContract for MyDynamicObject
        if (typeof(MyDynamicObject).IsAssignableFrom(objectType))
        {
            return CreateDynamicContract(objectType);
        }
        return base.CreateContract(objectType);
    }

    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        var properties = base.CreateProperties(type, memberSerialization);
        // If object type is a subclass of MyDynamicObject and the property is declared
        // in a subclass of MyDynamicObject, assume it is marked with JsonProperty 
        // (unless it is explicitly ignored).  By checking IsSubclassOf we ensure that 
        // "bookkeeping" properties like Count, Keys and Values are not serialized.
        if (type.IsSubclassOf(typeof(MyDynamicObject)) && memberSerialization == MemberSerialization.OptOut)
        {
            foreach (var property in properties)
            {
                if (!property.Ignored && property.DeclaringType.IsSubclassOf(typeof(MyDynamicObject)))
                {
                    property.HasMemberAttribute = true;
                }
            }
        }
        return properties;
    }
}

然后,要使用合同解析器, 它在某处用于性能:

static IContractResolver resolver = new MyContractResolver();

然后做:

var settings = new JsonSerializerSettings
{
    ContractResolver = resolver,
};
string json = JsonConvert.SerializeObject(obj, settings);

示例 fiddle here.