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

后端 未结 3 1712
天涯浪人
天涯浪人 2021-02-03 19:11

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 lik

相关标签:
3条回答
  • 2021-02-03 19:38

    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

    0 讨论(0)
  • 2021-02-03 19:44

    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.

    0 讨论(0)
  • 2021-02-03 19:44

    To combine everything: use JToken for everything (Objects AND Arrays).

    JToken token = JToken.FromObject(someObjectOrArray);
    

    Then check through token.Type which JTokenType it is (Object, Array or otherwise).

    0 讨论(0)
提交回复
热议问题