C# Json:使用字典<;字符串,列表<;字符串>&燃气轮机;作为JProperty的内容值

C# Json:使用字典<;字符串,列表<;字符串>&燃气轮机;作为JProperty的内容值,c#,json.net,C#,Json.net,我正在使用Newtonsoft.Json包,希望添加一个Dictionary作为JProperty的内容参数 为此,我创建了以下示例代码 try { Dictionary<string, List<string>> fields = new Dictionary<string, List<string>>() { { "foo",

我正在使用
Newtonsoft.Json
包,希望添加一个
Dictionary
作为
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);
    }
试试看{
字典字段=新字典()
{
{
“福”,
新列表(){a”,“b”}
},
{
“酒吧”,
新列表(){“c”,“d”}
}
};
新JProperty(名称(字段),字段);
}
捕获(例外e){
控制台写入线(e);
}
我还为复制创造了一个游乐场

不幸的是,我得到了这个例外

System.ArgumentException:无法确定的JSON对象类型 类型 System.Collections.Generic.KeyValuePair
2[System.String,System.Collections.Generic.List
1[System.String]]。 位于Newtonsoft.Json.Linq.JValue.GetValueType(可空`1当前,对象 值)位于Newtonsoft.Json.Linq.JValue..ctor(对象值)位于 Newtonsoft.Json.Linq.JContainer.CreateFromContent(对象内容)
位于Newtonsoft.Json.Linq.JContainer.AddInternal(Int32索引,对象 内容,布尔值skipParentCheck)位于 Newtonsoft.Json.Linq.JContainer.AddInternal(Int32索引,对象 内容,布尔值skipParentCheck)位于 Newtonsoft.Json.Linq.JContainer.Add(对象内容)位于 Newtonsoft.Json.Linq.JArray..ctor(对象内容)位于 Newtonsoft.Json.Linq.JProperty..ctor(字符串名称、对象内容)
在Program.Main()中

有人知道代码出了什么问题吗


如果不可能,是否有任何建议的解决方法?

您可以从
字段创建
JToken
来序列化它,方法如下:


您可以从
字段
创建
JToken
来序列化它,方法如下:


它无法将
System.Collections.Generic.List
转换为
Newtonsoft.Json.Linq.JToken

如果只需要json字符串,则可以序列化:

publicstaticvoidmain()
{
试一试{
字典字段=新字典()
{
{
“福”,
新列表(){a”,“b”}
},
{
“酒吧”,
新列表(){“c”,“d”}
}
};
var json=JsonConvert.SerializeObject(字段);
var result=JsonConvert.DeserializeObject(json);
}
捕获(例外e){
控制台写入线(e);
}
}
如果需要JObject,可以使用动力学:

publicstaticvoidmain()
{
试试{
动态字段=新作业对象();
字段[“foo”]=新JArray(“a”、“b”);
字段[“bar”]=新的JArray(“c”、“d”);
}
捕获(例外e){
控制台写入线(e);
}
}

它无法将
System.Collections.Generic.List
转换为
Newtonsoft.Json.Linq.JToken

如果只需要json字符串,则可以序列化:

publicstaticvoidmain()
{
试一试{
字典字段=新字典()
{
{
“福”,
新列表(){a”,“b”}
},
{
“酒吧”,
新列表(){“c”,“d”}
}
};
var json=JsonConvert.SerializeObject(字段);
var result=JsonConvert.DeserializeObject(json);
}
捕获(例外e){
控制台写入线(e);
}
}
如果需要JObject,可以使用动力学:

publicstaticvoidmain()
{
试试{
动态字段=新作业对象();
字段[“foo”]=新JArray(“a”、“b”);
字段[“bar”]=新的JArray(“c”、“d”);
}
捕获(例外e){
控制台写入线(e);
}
}
JProperty property = new JProperty(nameof(fields), JToken.FromObject(fields));