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.
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"]}}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With