Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argument Exception when creating JObject

Tags:

json

c#

json.net

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?

like image 262
Nii Laryea Avatar asked Aug 28 '13 19:08

Nii Laryea


People also ask

Can not add JValue to JObject?

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 ).

Is JObject parse slow?

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.

What does JObject parse do?

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.

What is JObject and JToken in C#?

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.


1 Answers

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"" }"); 
like image 194
Brian Rogers Avatar answered Sep 20 '22 13:09

Brian Rogers