Newtonsoft JsonSerializer - Lower case properties and dictionary

Liero picture Liero · Dec 3, 2015 · Viewed 75.3k times · Source

I'm using json.net (Newtonsoft's JsonSerializer). I need to customize serialization in order to meet following requirements:

  1. property names must start with lower case letter.
  2. Dictionary must be serialized into jsonp where keys will be used for property names. LowerCase rule does not apply for dictionary keys.

for example:

var product = new Product();
procuct.Name = "Product1";
product.Items = new Dictionary<string, Item>();
product.Items.Add("Item1", new Item { Description="Lorem Ipsum" });

must serialize into:

{
  name: "Product1",
  items : {
    "Item1": {
       description : "Lorem Ipsum"
    }
  }
}

notice that property Name serializes into "name", but key Item1 serializes into "Item1";

I have tried to create CustomJsonWriter to serialize property names, but it changes also dicionary keys.

public class CustomJsonWriter : JsonTextWriter
{
    public CustomJsonWriter(TextWriter writer) : base(writer)
    {

    }
    public override void WritePropertyName(string name, bool escape)
    {
        if (name != "$type")
        {
            name = name.ToCamelCase();
        }
        base.WritePropertyName(name, escape);
    }
}

Answer

Craig W. picture Craig W. · Dec 3, 2015

You could try using the CamelCasePropertyNamesContractResolver.

var serializerSettings = new JsonSerializerSettings();
serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
var json = JsonConvert.SerializeObject(product, serializerSettings);

I'm just not sure how it'll handle the dictionary keys and I don't have time right this second to try it. If it doesn't handle the keys correctly it's still worth keeping in mind for the future rather than writing your own custom JSON writer.