I have problem with serializing objects using Newtonsoft.JSON. I have a method which creates EventGridEvent object:
public EventGridEvent CreateEvent(object data) =>
new EventGridEvent
{
Id = Guid.NewGuid().ToString(),
EventTime = DateTime.Now,
Data = JObject.FromObject(data, JsonSerializer),
...other properties
}
When the method is called with "proper" object, everything serializes properly. The problem is if the data is a plain value i.e. integer or string. In this case I get an exception Object serialized to Integer. JObject instance expected. How to detect if object can be serialized with JObject.FromObject
and if not use its plain value (without using try/catch)?