0

I am trying to de-serialize JSON with snake case (Linqpad code)

    var payload = @"{ ""account_code"" : ""ABCD""}";
    var item = JsonConvert.DeserializeObject<System.Dynamic.ExpandoObject>(payload,
    new JsonSerializerSettings
    {
        DateFormatString = "yyyy-MM-dd",
        FloatParseHandling = FloatParseHandling.Decimal,
        ContractResolver = new DefaultContractResolver
        {
            NamingStrategy = new SnakeCaseNamingStrategy{ ProcessDictionaryKeys = true }
        }
    }
    );

    item.Dump();

But the ExpandoObject I get has attribute account_code instead of accountCode

Works fine if I use a custom type instead of ExpandoObject

What is the correct way to get camel case property with ExpandoObject?

Anand
  • 1,387
  • 2
  • 26
  • 48
  • Naming strategies only work in one direction, mapping from .Net names to JSON names **during serialization**. As such [`NamingStrategy`](https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Serialization_NamingStrategy.htm) has [`ResolvePropertyName`](https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Serialization_NamingStrategy_ResolvePropertyName.htm) mapping .Net => JSON but no corresponding *`UnresolveName`* for going the other way. For deserializing to a POCO the contract resolver itself does the reverse lookup, but that doesn't apply to dictionary deserialization. – dbc Feb 17 '21 at 21:03
  • For confirmation see e.g. [Camel-cased property names + dictionary-as-object serialization = lossy conversion #1023](https://github.com/JamesNK/Newtonsoft.Json/issues/1023#issuecomment-247514531): *Yes changing the dictionary key on serialization is lossy. That is by design. That is why I defaulted it to off with NamingStrategy. I believe it is also off by default with MVC Core.*. – dbc Feb 17 '21 at 21:04
  • You would need to write a custom `JsonConverter` for ExpandoObject to un-snake-case the property names, modeled e.g. on [`ExpandoObjectConverter`](https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/Converters/ExpandoObjectConverter.cs). Or maybe see [this answer](https://stackoverflow.com/a/53783120/3744182) to [Convert JSON camel case to snake case (and vice versa) and stringify numeric values](https://stackoverflow.com/q/53779796/3744182) for an alternate approach with readers and writers. – dbc Feb 17 '21 at 21:07
  • @dbc I will have to go thorough large amount of data so I suppose I will use a custom type instead of `ExpandoObject` for performance. Snake to came case works for custom type. – Anand Feb 17 '21 at 21:53

0 Answers0