2

A class in a third-party library I am using has the same JSON property name specified for two properties on a class. E.g. like this:

    public class Foo
    {
        [JsonProperty("X")]
        public string X1 { get; set; }

        [JsonProperty("X")]
        public string X2 { get; set; }
    }

When I try to serialize an instance of that class to JSON, it throws an exception

var foo = new Foo { X1 = "a" };
var json = JsonConvert.SerializeObject(foo); // throws JsonSerializationException

JsonSerializationException: 'A member with the name 'X' already exists on 'Foo'. Use the JsonPropertyAttribute to specify another name.'

How can I configure the json serialization to ignore the property names specified in the JsonPropery attribute?

Note that I have no control over the definition of Foo and so cannot modify the attributes, etc.

I am not even using one of the conflicting properties, but the exception is still thrown when I specify NullValueHandling.Ignore in JsonSerializerSettings.

Ergwun
  • 12,579
  • 7
  • 56
  • 83
  • Why would you want to set two same key on different values for this object? – D-Shih Mar 25 '19 at 05:58
  • @D-Shih I don't. It's a third-party library. – Ergwun Mar 25 '19 at 06:14
  • You can do this with a custom `ContractResolver`. If you want to ignore all `[JsonProperty]` attributes, see [How to ignore JsonProperty(PropertyName = “someName”) when serializing json?](https://stackoverflow.com/q/20622492/10263). If you want to remap one or more of the `[JsonProperty]` names to something else, see [Json.NET deserialize or serialize json string and map properties to different property names defined at runtime](https://stackoverflow.com/q/38111298/10263). – Brian Rogers Mar 25 '19 at 06:15
  • Thanks @BrianRogers. I guess that means my question is a duplicate. – Ergwun Mar 25 '19 at 06:17
  • Yep, it looks that way. I'll close it. – Brian Rogers Mar 25 '19 at 06:17

0 Answers0