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

扶醉桌前 提交于 2019-12-09 04:39:05

问题


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?


回答1:


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




回答2:


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 below:

JArray jArray = JArray.FromObject(someArrayObject);

Please include using Newtonsoft.Json.Linq; at the top of your code file to use this code snippet.



来源:https://stackoverflow.com/questions/33088297/serialize-an-object-directly-to-a-jobject-instead-of-to-a-string-in-json-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!