Search code examples
c#jsonserializationjson.net

Serialize an object directly to a JObject instead of to a string in json.net


How might one serialize an object directly to a JObject instance in JSON.Net? What is typically done is to convert the object directly to a json string like so:

string jsonSTRINGResult = JsonConvert.SerializeObject(someObj);

One could then deserialize that back to a JObject as follows:

JObject jObj = JsonConvert.DeserializeObject<JObject>(jsonSTRINGResult);

That seems to work, but it would seem like this way has a double performance hit (serialize and then deserialize). Does SerializeObject internally use a JObject that can be accessed somehow? Or is there some way to just serialize directly to a JObject?


Solution

  • 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