> 作为 JProperty 的内容值,c#,json.net"/>

首页 > 解决方案 > 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.List1 [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()

有人知道代码有什么问题吗?

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

标签: c#json.net

解决方案


您可以使用like创建JTokenfrom以对其进行序列化:fieldsJToken.FromObject()

JProperty property = new JProperty(nameof(fields), JToken.FromObject(fields));

推荐阅读