3

Quick question about serialization in .NET (still pretty new to it).

I have a route that returns Dictionary<string, ArbirartyModel[]>. The issue is in the result. I've put expected and actual below. It seems to lower all characters up until 1 character before the first underscore, then leaves everything else below.

Expected

{
  TEST_ONE: "Value",
  TEST_TOW: "Value"
}

Actual

{
  tesT_ONE: "Value",
  tesT_TOW: "Value"
}

I've been looking around and it seems that this issue and a few others are related, but, unfortunately, I cannot change anything in the Global.asax

Any help would be very much appreciated.

Update

[HttpGet, Route("result/goes/here")]
public IHttpActionResult ReturnResult()
{
   return Ok(new Dictionary<string, string>() {{"TEST_ONE", "Value"}, {"TEST_TOW", "Value"}});
}

Ok is part of IHttpActionResult in Web API (https://msdn.microsoft.com/en-us/library/dn314591.aspx)

Community
  • 1
  • 1
vernak2539
  • 574
  • 3
  • 14
  • Can you post the code where you create the dictionary, and the code where you serialize it? – Bas Oct 05 '15 at 12:59
  • @Bas should be added up there. serialization happens in json.net – vernak2539 Oct 05 '15 at 13:03
  • I don't believe this is JSON.NET's doing. Show the actual implementation of `// add results here....`. See [mcve]. – CodeCaster Oct 05 '15 at 13:04
  • The results from the local window show keys like the expected data. So when `combinations.Select(x => x.key).ToArray()` is done the following is returned `["APP_INSTALLS", "TEST_STRING"]` – vernak2539 Oct 05 '15 at 13:09
  • Well I'm sorry but I can't reproduce this with a simple `return Ok(new Dictionary { { "CAPS", "Foo" } });`: it gives me `{ "CAPS": "Foo" }`. Perhaps you have some custom serializer or changed some serialization settings, or you're using a specific version of some library. Again, please read [mcve] and include all relevant details – CodeCaster Oct 05 '15 at 13:15

1 Answers1

2

You have JSON.NET configured to serialize property names using camel case. Unfortunately JSON.NET will treat Dictionary types the same as an object types in this respect by treating each key as an property name.

The offending configuration will look something like this:

JsonConvert.SerializeObject( <YOUR OBJECT>, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });

Sir Rippov the Maple
  • 7,491
  • 5
  • 42
  • 52