Argument Exception when creating JObject

C#Jsonjson.net

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNii LaryeaView Question on Stackoverflow
Solution 1 - C#Brian RogersView Answer on Stackoverflow