Pascal case dynamic properties with Json.NET

前端 未结 4 826
一整个雨季
一整个雨季 2020-12-06 15:57

This is what I have:

using Newtonsoft.Json;

var json = \"{\\\"someProperty\\\":\\\"some value\\\"}\";
dynamic deserialized = JsonConvert.DeserializeObject(j         


        
4条回答
  •  抹茶落季
    2020-12-06 17:04

    For newtonsoft add this attribute to your properties:

    [JsonProperty("schwabFirmId")]
    

    A simpler option (since you just need to do it once per class) if you are up for including MongoDB: try adding a reference to MongoDB.Bson.Serialization.Conventions.

    Then add this in your model constructor:

    var pack = new ConventionPack { new CamelCaseElementNameConvention(), new IgnoreIfDefaultConvention(true) };
                ConventionRegistry.Register("CamelCaseIgnoreDefault", pack, t => true);
    

    Either one will keep your favorite C# properties PascalCased and your json camelCased.

    Deserializing will treat the inbound data as PascalCased and serializing will change it into camelCase.

提交回复
热议问题