c# - Newtonsoft.Json:使用字典> 作为 JProperty 的内容值
问题描述
我正在使用该Newtonsoft.Json
包并希望将 aDictionary<string, List<string>>
作为内容参数添加到 a JProperty
。
为此,我创建了以下示例代码
try {
Dictionary<string, List<string>> fields = new Dictionary<string, List<string>>()
{
{
"foo",
new List<string>() { "a", "b" }
},
{
"bar",
new List<string>() { "c", "d" }
}
};
new JProperty(nameof(fields), fields);
}
catch (Exception e) {
Console.WriteLine(e);
}
我还为繁殖创造了一个游乐场
https://dotnetfiddle.net/OjyJ5u
不幸的是我得到了这个例外
System.ArgumentException:无法确定 System.Collections.Generic.KeyValuePair
2[System.String,System.Collections.Generic.List
1 [System.String]] 类型的 JSON 对象类型。在 Newtonsoft.Json.Linq.JValue.GetValueType(Nullable`1 current, Object value) 在 Newtonsoft.Json.Linq.JValue..ctor(Object value) 在 Newtonsoft.Json.Linq.JContainer.CreateFromContent(Object content)
在 Newtonsoft .Json.Linq.JContainer.AddInternal(Int32 index, Object content, Boolean skipParentCheck) at Newtonsoft.Json.Linq.JContainer.AddInternal(Int32 index, Object content, Boolean skipParentCheck) at Newtonsoft.Json.Linq.JContainer.Add(Object content) 在 Newtonsoft.Json.Linq.JArray..ctor(Object content) 在 Newtonsoft.Json.Linq.JProperty..ctor(String name, Object content)
在 Program.Main()
有人知道代码有什么问题吗?
如果这不可能,是否有任何建议的解决方法?
解决方案
您可以使用like创建JToken
from以对其进行序列化:fields
JToken.FromObject()
JProperty property = new JProperty(nameof(fields), JToken.FromObject(fields));
推荐阅读
- html - 让 flexbox 容器内的文本换行和溢出:自动工作
- javascript - 递归解释倒计时功能,多种方法
- javascript - 页面生命周期 API
- python - 无法打开 Anaconda
- typescript - 在 Typescript 中省略属性的扩展
- laravel - 在 API 中保存后如何返回 eloquent 查询结果 - Laravel
- vim - 想要地图
滚动以前的冒号命令 - javascript - 如何使用谷歌应用脚本在谷歌文档中获取字符串的索引
- google-analytics - Google Analytics(分析)新媒体 App+Web 是否有衡量协议?
- javascript - ArrayBuffer 内存泄漏和火狐内存工具