c# - Keep casing when serializing dictionaries -


i have web api project being configured this:

config.formatters.jsonformatter.serializersettings.contractresolver = new camelcasepropertynamescontractresolver(); 

however, want dictionary keys casing remain unchanged. there attribute in newtonsoft.json can use class denote want casing remain unchanged during serialization?

public class someviewmodel {     public dictionary<string, string> data { get; set; }     } 

there not attribute this, can customizing resolver.

i see using camelcasepropertynamescontractresolver. if derive new resolver class , override createdictionarycontract() method, can provide substitute dictionarykeyresolver function not change key names.

here code need:

class camelcaseexceptdictionarykeysresolver : camelcasepropertynamescontractresolver {     protected override jsondictionarycontract createdictionarycontract(type objecttype)     {         jsondictionarycontract contract = base.createdictionarycontract(objecttype);          contract.dictionarykeyresolver = propertyname => propertyname;          return contract;     } } 

demo:

class program {     static void main(string[] args)     {         foo foo = new foo         {             anintegerproperty = 42,             htmlstring = "<html></html>",             dictionary = new dictionary<string, string>             {                 { "whizbang", "1" },                 { "foo", "2" },                 { "bar", "3" },             }         };          jsonserializersettings settings = new jsonserializersettings         {             contractresolver = new camelcaseexceptdictionarykeysresolver(),             formatting = formatting.indented         };          string json = jsonconvert.serializeobject(foo, settings);         console.writeline(json);     } }  class foo {     public int anintegerproperty { get; set; }     public string htmlstring { get; set; }     public dictionary<string, string> dictionary { get; set; } } 

here output above. notice of class property names camel-cased, dictionary keys have retained original casing.

{   "anintegerproperty": 42,   "htmlstring": "<html></html>",   "dictionary": {     "whizbang": "1",     "foo": "2",     "bar": "3"   } } 

Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -