JSON.Net Duplicate properties on Serialization of derived object where base contains Dictionary Properties

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-12 16:52:27

问题


I currently have a problem whereby when I serialize a class that derives from a base class that contains a Dictionary property, duplicate properties are serialized to JSON.

The derived class contains a concrete property definition AND the dictionary in the base class contains a property of the same name at runtime. Upon Serialization the generated JSON string will contain two of the same property which is invalid JSON and will trip up Deserializers.

I need a generic way for the derived class concrete implementation properties to take precedence over anything contained within the base class Dictionary of properties derived from base.

Example JSON after serialization:

{ "myProperty": "I should have precedence", "myProperty": "I shouldn't be here!" }

The Class definitions look like this:

public class Base
{
    [JsonExtensionData]
    public Dictionary<string, object> Properties { get; set; }
}

public class Child : Base
{
    [JsonProperty("myProperty")]
    public string MyProperty { get; set; }
}

Example Usage:

static void Main(string[] args)
{
    Child child = new Child()
    {
        Properties = new Dictionary<string, object>() { { "myProperty", "I shouldn't be here!" } }
    };
    child.MyProperty = "I should have precedence";
    string serializedObject = JsonConvert.SerializeObject(child);
    Console.WriteLine(serializedObject); // duplicates are present!
}

I wish to load dynamic json properties and values using the base dictionary and in any derived classes have access to this. If the derived class has a concrete implementation the derived class property implementation should take precedence.

I was under the impression that JsonExtensionData would configure the Json.Net serializer to do this.

Using Conditional Serialization could work, but it only seems that it's only possible to set whether the public property can be serialized as opposed to the individual Key Value Pairs within the Property Dictionary.

ShouldSerializeProperties()
{
    // reflect over class properties
    // store reflected property names in a list
    // iterate over reflected property names and check to see if each property
    // name exists as a key in the Properties Dictionary
    // set return value
    // once loop finished, return the return value
}

So essentially I'm after an opt-in serialization on values of properties, the above example won't work because the serializer will not serialize any of the dynamic property key value pairs in the dictionary of properties as ShouldSerializeMyProperty applies to the whole property - as it should. Any help would be appreciated!

来源:https://stackoverflow.com/questions/33434251/json-net-duplicate-properties-on-serialization-of-derived-object-where-base-cont

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!