JamesNK / Newtonsoft.Json

Json.NET is a popular high-performance JSON framework for .NET
https://www.newtonsoft.com/json
MIT License
10.64k stars 3.24k forks source link

Ignoring JsonProperty Name #2964

Closed ahmetkoprulu closed 3 weeks ago

ahmetkoprulu commented 3 weeks ago

Source/destination types

    public class UserEvent
    {
        [JsonProperty("s")] public string ScheduleId { get; set; }
        [JsonProperty("i")] public string EventId { get; set; }
    }

Source/destination JSON

{ "s": "test", "I": "test" }

Expected behavior

I want to ignore the JsonProperty attribute manually by passing serializer settings or something else. Is it possible to achieve this behavior? I could not find any resource about it.

elgonzo commented 3 weeks ago

Implement a custom contract resolver deriving from DefaultContractResolver. Override its CreateProperty method in such a way that it:

  1. obtains the JsonProperty instance from the base CreateProperty method.
  2. sets the json property name of the obtained JsonProperty instance to the name of the MemberInfo passed into the CreateProperty method.
  3. returns the modified JsonProperty instance.

This basically sets the json property names to the names of the respective .NET instance field/property names, effectively undoing any custom json property name taken from [JsonProperty]. (Additionally, if necessary, make this dependent on the value of the JsonProperty.DeclaringType property to limit this behavior only to properties/fields in desired types.)

Then assign this custom contract resolver to the ContractResolver property of the JsonSerializerSettings used for (de)serialization, and Bob should be your uncle...

ahmetkoprulu commented 3 weeks ago

Thanks for the answer. It seems like that would work. I am closing the issue.