Newtonsoft.Json:使用 Dictionary<string, List<string>> 作为 JProperty

时间:2021-01-05 10:25:36

标签: c# json.net

我正在使用 Newtonsoft.Json 包,并希望将 Dictionary<string, List<string>> 作为内容参数添加到 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:无法确定 JSON 对象类型 类型 System.Collections.Generic.KeyValuePair2[System.String,System.Collections.Generic.List1[System.String]]。 在 Newtonsoft.Json.Linq.JValue.GetValueType(Nullable`1 current, Object 值)在 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(Object content) 在 Newtonsoft.Json.Linq.JArray..ctor(Object content) 在 Newtonsoft.Json.Linq.JProperty..ctor(String name, Object content)
在 Program.Main()

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

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

2 个答案:

答案 0 :(得分:2)

您可以使用 JToken.FromObject()select case when b.max_day <= '30' and a.c in ('A','B','C') and a.d not in ('1','2') then a.amount end as amount_30 from yourtable a join (select max(a.day) as max_day, a.id as id_customer from table a group by a.id) b on a.id=b.id_customer 创建 JToken 以对其进行序列化,例如:

fields

答案 1 :(得分:0)

它不能将 System.Collections.Generic.List<string> 转换为 Newtonsoft.Json.Linq.JToken

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

public static void Main()
    {
        try {
            Dictionary<string, List<string>> fields = new Dictionary<string, List<string>>()
            {
                {
                    "foo",
                    new List<string>() { "a", "b" }
                },
                {
                    "bar",
                    new List<string>() { "c", "d" }
                }
            };
            
            var json = JsonConvert.SerializeObject(fields);
            var result = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(json);
        }
        catch (Exception e) {
            Console.WriteLine(e);
        }
    }

如果你想要一个 JObject,你可以使用动态:

    public static void Main()
    {
        try {           
            dynamic fields = new JObject();
            fields["foo"] = new JArray("a", "b");
            fields["bar"] = new JArray("c", "d");
        }
        catch (Exception e) {
            Console.WriteLine(e);
        }
    }