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)?
If EventGridEvent.Data
can hold any type of JSON value, you should modify it to be of type JToken
and use JToken.FromObject(Object, JsonSerializer)
, i.e.:
public class EventGridEvent
{
public JToken Data { get; set; }
// ...other properties
}
And then do
Data = JToken.FromObject(data, JsonSerializer),
A JToken
Represents an abstract JSON token.
It can be used to hold the JSON representation of any JSON type including an array, object, or primitive value. See: JSON.NET: Why Use JToken--ever?.