Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newtonsoft JsonSerializer - Lower case properties and dictionary [duplicate]

Tags:

c#

json.net

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);     } } 
like image 281
Liero Avatar asked Dec 03 '15 15:12

Liero


People also ask

Should JSON properties be LowerCase?

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

Is Newtonsoft JsonSerializer thread safe?

Correct, JsonSerializer is threadsafe.

What is Jsonproperty annotation C#?

JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in. It includes non-public properties in serialization and deserialization. It can be used to customize type name, reference, null, and default value handling for the property value.

What is CamelCasePropertyNamesContractResolver?

CamelCasePropertyNamesContractResolver. CamelCasePropertyNamesContractResolver inherits from DefaultContractResolver and simply overrides the JSON property name to be written in camelcase. ContractResolver.


1 Answers

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.

like image 114
Craig W. Avatar answered Sep 26 '22 10:09

Craig W.