Hope that someone can help me with this seemingly simple problem. In short, I want to use camel case for all property names, except when the property is a DataTable. In that case, I want the column names to be unchanged when serialized.
I have a rather deep object structure that I serialize to JSON, using JSON.NET. I want the property names to be camel case, and I dont want to put attributes on every class, so I use the following code:
public static class JsonHelper
{
private static DefaultContractResolver _contractResolver = new DefaultContractResolver()
{
NamingStrategy = new CamelCaseNamingStrategy()
};
public static string SerializeObjectToJson(object obj)
{
string json = JsonConvert.SerializeObject(obj, new JsonSerializerSettings
{
ContractResolver = _contractResolver
});
return json;
}
}
...
string json = JsonHelper.SerializeObjectToJson(myDataDTO);
That works fine. However, I also have ADO.NET DataTable properties, and in that case I want to keep the case of the column names unchanged.
Simplified example here:
public class MySampleDTO
{
public Object Data { get; init; }
public int SomeInteger { get; init; }
}
...
// Get table with columns "Period", "Sales" and "Expenses"
DataTable myDataTable = ...
MySampleDTO dto = new MySampleDTO() {
Data = myDataTable,
SomeInteger = 3
}
string json = JsonHelper.SerializeObjectToJson(dto);
The resulting JSON becomes:
{
"data": [
{
"period": "2004",
"sales": 400,
"expenses": 700
},
{
"period": "2005",
"sales": 500,
"expenses": 900
},
{
"period": "2006",
"sales": 720,
"expenses": 420
}
],
"someInteger": 3
}
Obviously, the column names of the data table are serialized as camelcase which is not what I want (but I want "SomeInteger" to be camel case)
Any ideas how I can solve this?