1

I've created this kind of class and I just serialized an instance with JsonConvert.SerializeObject(instance);

public sealed class MetadataList : Dictionary<string, Metadata>, IEnumerable<Metadata>
{
    [JsonProperty("F")]
    public FormatEnum Format { get; set; }

    //...
}

The result was as I expect a serialized dictionary just the Format property wasn't presented. So I've marked the class as JsonObject.

[JsonObject]
public sealed class MetadataList
{
    //...
}

Then the json contained all of the Dictionary<> base class's properties. So I tried to overwrite them just like this.

public sealed class MetadataList : Dictionary<string, Metadata>, IEnumerable<Metadata>
{
    [JsonProperty("F")]
    public FormatEnum Format { get; set; }

    [JsonProperty("V")]
    public new IEnumerable<Metadata> Values { get { return base.Values; } }

    [JsonIgnore]
    public new int Count { get { return base.Count; } }

    [JsonIgnore]
    public new IEqualityComparer<string> Comparer { get { return base.Comparer; } }

    [JsonIgnore]
    public new IEnumerable<string> Keys { get { return base.Keys; } }

    //...
}

Than the json contained the union of the base class and my class properties except the ignored properties, so the json was contained the "Values":[...] and "V":[...] as well which are the same. Meanwhile I was writing my class JsonConverter I realized the following.

JsonObjectContract contract = (JsonObjectContract)serializer.ContractResolver.ResolveContract(value.GetType());
var properties = contract.Properties;

The contract.Properties contained the my class F and V JsonProperties and contained the base class Values, Count, Comparer and Keys JsonProperties and the internal SerializeObject method iterate on this properties and serialize all of them.

I just want to know is that a bug in the serialization or this is the expected behavior? Because my point of view I have hided the base class properties so instead of those the properties should contain mine. I managed it in my JsonConverter so everything is fine just I have to write more test what is not a problem.

If anybody knows how to ignore a base class property without JsonConverter then I would welcome the solution. Thanks

dbc
  • 104,963
  • 20
  • 228
  • 340
bandolir
  • 41
  • 4
  • This is expected behavior. See [this similar question](http://stackoverflow.com/q/26215578/10263). Also see [here](http://stackoverflow.com/q/159978/10263) to understand the difference between `new` and `override`. – Brian Rogers Nov 04 '14 at 17:14
  • You can use `[JsonObject(MemberSerialization = MemberSerialization.OptIn)]` to suppress serialization of base class properties. See [Json.Net cannot serialize property of a class derived from dictionary](https://stackoverflow.com/questions/39084536/json-net-cannot-serialize-property-of-a-class-derived-from-dictionary/39087175#39087175). – dbc Nov 10 '16 at 17:59

0 Answers0