Serialize an object directly to a JObject instead of to a string in json.net
Please note that the JObject
route suggested by @Eser will work only for non-array CLR objects. It results in below exception if you try converting an Array object to JObject
:
An unhandled exception of type 'System.InvalidCastException' occurred in Newtonsoft.Json.dll
Additional information: Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'Newtonsoft.Json.Linq.JObject'.
So, in case it is an array object then you should be using JArray
instead as shown in the code snippet below:
using Newtonsoft.Json.Linq;
JArray jArray = JArray.FromObject(someArrayObject);
You can use FromObject
static method of JObject
JObject jObj = JObject.FromObject(someObj)
http://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JObject_FromObject.htm