简体   繁体   中英

Serializing plain values and objects with JObject.FromObject

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 ie 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) , ie:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM