Ensuring json keys are lowercase in .NET

后端 未结 5 2059
生来不讨喜
生来不讨喜 2020-11-28 02:25

Is there simple way using JSON in .NET to ensure that the keys are sent as lower case?

At the moment I\'m using the newtonsoft\'s Json.NET library and simply using

5条回答
  •  醉话见心
    2020-11-28 03:19

    In Json.NET 9.0.1 and later it is possible to ensure that all property names are converted to lowercase by using a custom NamingStrategy. This class extracts the logic for algorithmic remapping of property names from the contract resolver to a separate, lightweight object that can be set on DefaultContractResolver.NamingStrategy. Doing so avoids the need to create a custom ContractResolver and thus may be easier to integrate into frameworks that already have their own contract resolvers.

    Define LowercaseNamingStrategy as follows:

    public class LowercaseNamingStrategy : NamingStrategy
    {
        protected override string ResolvePropertyName(string name)
        {
            return name.ToLowerInvariant();
        }
    }
    

    Then serialize as follows:

    var settings = new JsonSerializerSettings
    {
        ContractResolver = new DefaultContractResolver { NamingStrategy = new LowercaseNamingStrategy() },
    };
    string loginRequest = JsonConvert.SerializeObject(auth, settings);
    

    Notes -

    • Using string.ToLowerInvariant() ensures that the same contract is generated in all locales.

    • To control whether overridden property names, dictionary keys and extension data names are lowercased, you can set NamingStrategy.OverrideSpecifiedNames, NamingStrategy.ProcessDictionaryKeys or NamingStrategy.ProcessExtensionDataNames (Json.NET 10.0.1 and later) to true.

    • You may want to cache the contract resolver for best performance.

    • If you do not have access to the serializer settings in your framework, you can apply a NamingStrategy directly to your object as follows:

      [JsonObject(NamingStrategyType = typeof(LowercaseNamingStrategy))]
      public class Authority
      {
          public string Username { get; set; }
          public string ApiToken { get; set; }
      }
      
    • Do not modify the NamingStrategy of CamelCasePropertyNamesContractResolver. This contract resolver shares type information globally across all of its instances, and so modifying any one instance can have unexpected side effects.

提交回复
热议问题