Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get newtonsoft to camelcase object properties

Tags:

c#

json.net

I've got the following code which newtonsoft camelcases the top level of properties but not the properties passed in as Object.

public class Event
{
    public int Id { get; set; }
    public string Name { get; set; }
    public object Body { get; set; }
}

Here is my test:

public void Test()
{
    var json = @"
        {
            'Id': 2,
            'Name': 'Foo',
            'Body': {
                'ShipmentId':'6983136',
                'PickupDate':'2019-07-26T17:14:11Z',
                'OrderNumbers':['9638063']
            }
        }";

    var myEvent = JsonConvert.DeserializeObject<Event>(json);
    var camelSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
    var endJson = JsonConvert.SerializeObject(myEvent, camelSettings);
    Console.WriteLine(endJson);
}

This outputs:

{"id":2,"name":"Foo","body":{"ShipmentId":"6983136","PickupDate":"2019-07-26T17:14:11Z","OrderNumbers":["9638063"]}}

How do I get it to camelcase the properties inside of body.

like image 340
DanielEli Avatar asked Jan 26 '23 00:01

DanielEli


2 Answers

One solution would be to use ExpandoObject. For example,

var myEvent = JsonConvert.DeserializeObject<ExpandoObject>(json); // Deserialize as ExpandoObject
var camelSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
var endJson = JsonConvert.SerializeObject(myEvent, camelSettings);

Please note that above code Deserialize the json as ExpandoObject instead of Event. This would produce as endJson as

{"id":2,"name":"Foo","body":{"shipmentId":"6983136","pickupDate":"2019-07-26T17:14:11Z","orderNumbers":["9638063"]}}
like image 105
Anu Viswan Avatar answered Jan 30 '23 02:01

Anu Viswan


I have faced this issue before. It is because of type object.

You can get fix it by creating a class for body or follow this link https://andrewlock.net/serializing-a-pascalcase-newtonsoft-json-jobject-to-camelcase/#3-convert-a-pascalcase-jobject-to-camelcase

If you follow the link. You have to convert it first into JObject using below code

var myEvent = JObject.Parse(json);  
var endJson = JsonConvert.SerializeObject(myEvent.ToCamelCaseJToken(), camelSettings);
like image 42
sydeng Avatar answered Jan 30 '23 01:01

sydeng