If I have this method:
public void doSomething (Dictionary<String, Object> data) { JObject jsonObject = new JObject(data); ... }
I get a System.ArgumentException
on the line where I create the JObject. I'm using Newton-King's Json.net wrapper.
The error I get is:
A first chance exception of type 'System.ArgumentException' occurred in Newtonsoft.Json.DLL An exception of type 'System.ArgumentException' occurred in Newtonsoft.Json.DLL but was not handled in user code
What am I doing wrong here?
You are getting this error because you are trying to construct a JObject with a string (which gets converted into a JValue ). A JObject cannot directly contain a JValue , nor another JObject , for that matter; it can only contain JProperties (which can, in turn, contain other JObjects , JArrays or JValues ).
That being said, it's known that parsing to JObject can be slower than deserializing -- see stackify.com/top-11-json-performance-usage-tips which states, Parsing generic JSON to a JSON.net JObject ... is slower (~20%) than reading that data in to a defined class type.
Jobject. Parse() method is an object class method and this method is used to parse the JSON string into the objects of C#. Based on the key value it parses the data of string and then it retrieves the data by using the key values.
A JToken is a generic representation of a JSON value of any kind. It could be a string, object, array, property, etc. A JProperty is a single JToken value paired with a name. It can only be added to a JObject, and its value cannot be another JProperty. A JObject is a collection of JProperties.
The JObject(object)
constructor is expecting the object to be either a JProperty
, an IEnumerable
containing JProperties
, or another JObject
. Unfortunately, the documentation does not make this clear.
To create a JObject
from a dictionary or plain object, use JObject.FromObject
instead:
JObject jsonObject = JObject.FromObject(data);
To create a JObject
from a JSON string, use JObject.Parse
, e.g.:
JObject jsonObject = JObject.Parse(@"{ ""foo"": ""bar"", ""baz"": ""quux"" }");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With