Newtonsoft JsonSerializer - Lower case properties and dictionary

C#json.net

C# Problem Overview


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);
    }
}

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

You can use a JsonProperty to change how something is serialized/deserialized. When you define your object add the property items to the fields you would like represented differently in the JSON. This only works with NewtonsoftJSON. Other libraries may do it differently.

public class Product
{
    [JsonProperty("name")]
    public string Name { get; set; }
    
    [JsonProperty("items")]
    public Dictionary<string, Item> Items { get; set; }
}

public class Item
{
    [JsonProperty("description")]
    public string Description { get; set; }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLieroView Question on Stackoverflow
Solution 1 - C#Craig W.View Answer on Stackoverflow
Solution 2 - C#Brian from state farmView Answer on Stackoverflow