Argument Exception when creating JObject

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?


Solution 1:

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"" }");