c# - 创建 JObject 时出现参数异常

如果我有这个方法:

public void doSomething (Dictionary<String, Object> data)
{
    JObject jsonObject = new JObject(data);
    ...
}

我在创建 JObject 的那一行得到一个 System.ArgumentException。我正在使用 Newton-King 的 Json.net 包装器。

我得到的错误是:

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

我在这里做错了什么?

最佳答案

JObject(object) 构造函数期望对象是一个 JProperty,一个包含 JPropertiesIEnumerable >,或另一个 JObject。不幸的是,文档没有说明这一点。

要从字典或普通对象创建 JObject,请使用 JObject.FromObject而是:

JObject jsonObject = JObject.FromObject(data);

要从 JSON 字符串创建 JObject,请使用 JObject.Parse ,例如:

JObject jsonObject = JObject.Parse(@"{ ""foo"": ""bar"", ""baz"": ""quux"" }");

https://stackoverflow.com/questions/18496129/

相关文章:

json - 将 JSON 序列化程序添加到每个模型类?

ruby-on-rails - 在rails中渲染json的最快方法是什么

javascript - 如何将 jQuery.serialize() 数据转换为 JSON 对象?

android - 在android中创建json

php - 将 JSON 数据从 Javascript 发送到 PHP?

arrays - 如何在 json 模式中定义数组的最小大小

django - 如何使用 Django REST 框架制作 POST 简单的 JSON? CSRF

java - 如何使用 getJSONArray 方法访问 json 对象的嵌套元素

json - 带有 Play 2.2 库的密封特征的无噪声 JSON 格式

python - 将 json 字符串转换为 python 对象