将JSON转换为有序词典列表,然后将Add()返回到新列表



我正试图使用Newtonsoft JSON读取JSON文件的内容,这是一个字典列表,对它们进行迭代,并在找出我不想要的字典后创建一个新的字典列表,该列表最终将写回JSON文件。

无论我尝试什么,我似乎都无法将其列表中的JSON条目添加回新的列表。错误如下:

Unhandled Exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 
The best overloaded method match for 'System.Collections.Generic.List<System.Collections.Specialized.OrderedDictionary>.Add(System.Collections.Specialized.OrderedDictionary)' 
has some invalid arguments

这是我反序列化的JSON字符串:

[
    {
        "name":"test",
        "custom":false,
        "file":"strawberry-perl-5.10.1.2portable.zip",
        "url":"http://strawberryperl/....",
        "ver":"5.10.1",
        "csum":"f86ae4b14daf0b1162d2c4c90a9d22e4c2452a98"
    }
]

这是我的代码:

dynamic customPerlList = JsonParse("perls_custom");
List<dynamic> updatedList = new List<dynamic>();
foreach (var perlStruct in customPerlList)
{
    if (perlStruct.name != perlVersionToRemove)
    {
        Console.WriteLine("match");
        updatedList.Add((OrderedDictionary)perlStruct);
    }
}

我刚开始在C#中进行开发,所以我尝试使用搜索时发现的示例,要么没有被理解,要么遗漏了其他内容。有人能指出我的错误吗?做我正在尝试的事情的正确方法是什么?

最可能的问题是无类型JSON对象通常与.NET库中的IDictionary<string, object>接口匹配;OrderedDictionary没有该接口。实际上,JSON对象并不被认为是有序的。

也许您可以切换到使用常规的Dictionary<string, object>,或者编写一个特定的类来序列化到/从。

如果你想使用Dictionary<string, object>,那么你应该考虑反序列化如下:

var list = JsonConvert.ToObject<List<Dictionary<string, object>>>(s);

最新更新