0

I'm using a DefaultcontractResolver with CamelCaseNamingStrategy to serialize my dictionaries. For reasons outside my control, I temporarily have to serialize a single dictionary to PascalCase. Yet, I can't seem to get it to work.

I set up my serializer as follows

        var defaultSerializerSettings = new JsonSerializerSettings
        {
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            NullValueHandling = NullValueHandling.Ignore,
            Converters = new List<JsonConverter> { new Newtonsoft.Json.Converters.StringEnumConverter(new CamelCaseNamingStrategy()) },
        };
        defaultSerializerSettings.ContractResolver = new DefaultContractResolver
        {
            NamingStrategy = new CamelCaseNamingStrategy
            {
                OverrideSpecifiedNames = true,
                ProcessDictionaryKeys = true
            }
        };

My test class has two dictionaries, one that is supposed to be serialized per default, so camelCase with dictionary keys, and then one where it's supposed to be camelCase but leaving dictionary keys alone

    internal class TestClass
    {
        [JsonProperty(NamingStrategyType = typeof(CamelCaseNamingStrategy), NamingStrategyParameters = new object[] { true, false })]
        public Dictionary<string, string> CSVImportFileFieldMapping { get; set; }

        public Dictionary<string, string> CSVImportFileFieldMapping2 { get; set; }
    }

And then I create a testobject and serialize it

    var pb = new TestClass
    { 
        CSVImportFileFieldMapping = new Dictionary<string, string> { { "Hello", "World" }, { "Gaga", "Gugu" } },
        CSVImportFileFieldMapping2 = new Dictionary<string, string> { { "Hello", "World" }, { "Gaga", "Gugu" } },
    };
    var jsonString = JsonConvert.SerializeObject(pb, defaultSerializerSettings);

Yet, both dictionaries have their keys pascalCased.

Any idea what I'm missing here?

Stephan Steiner
  • 1,043
  • 1
  • 9
  • 22
  • 1
    [`JsonPropertyAttribute.NamingStrategyType`](https://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_JsonPropertyAttribute_NamingStrategyType.htm) only applies to the *name of the property itself*. It does not control the names of any properties contained in the value of the property to which the attribute is applied. See: [How to make Json Serialize ignore dictionary keys](https://stackoverflow.com/a/58509729/3744182), which looks to be a duplicate. Agree? – dbc Oct 07 '20 at 16:24
  • 1
    I implemented approach #3, which does indeed work. so it is a duplicate. – Stephan Steiner Oct 22 '20 at 13:04

0 Answers0