Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 353
Nicholas Petersen Avatar asked Oct 12 '15 18:10

Nicholas Petersen


People also ask

What is serializing and deserializing JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).

What is JSON serialization in C#?

Serialization is the process of converting . NET objects such as strings into a JSON format and deserialization is the process of converting JSON data into . NET objects. In this article and code examples, first we will learn how to serialize JSON in C# and then we will learn how to deserialize JSON in C#.


2 Answers

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

like image 124
Eser Avatar answered Oct 14 '22 09:10

Eser


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); 
like image 25
RBT Avatar answered Oct 14 '22 08:10

RBT