1

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)?

dbc
  • 104,963
  • 20
  • 228
  • 340
vanpersil
  • 764
  • 1
  • 8
  • 26
  • Why not just do `JToken.FromObject()` and modify `Data` to be of type `JToken`? a `JToken` can represent any sort of JSON value, not just an object. See: [JSON.NET: Why Use JToken--ever?](https://stackoverflow.com/q/38211719/3744182). – dbc Feb 03 '20 at 18:20
  • 1
    Yes - this is exactly what I need. Thank you so much - if you wish, please copy it to the answer, so that I can mark it as accepted. – vanpersil Feb 03 '20 at 18:28

2 Answers2

2

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?.

dbc
  • 104,963
  • 20
  • 228
  • 340
0

If you need to serialize a nullable value like an int? or string, JToken.FromObject() will throw an error. I've found that the implicit operator (called by casting) works better.

string s = null;
int? i = null;
JObject obj = new JObject();

// obj.Add(JToken.FromObject(s)); // throws exception
// obj.Add(JToken.FromObject(i)); // throws exception

obj.Add((JToken)s); // works
obj.Add((JToken)i); // works
muusbolla
  • 637
  • 7
  • 20