你可以将JSON字符串反序列化为C#数组吗?

3 c# arrays json deserialization

我正在尝试反序列化JSON字符串

[{ "key" : "1", "value" : "open"}, {"key" : "2", "value" : "closed"}, {"key" : "3", "value" : "pending"}]
Run Code Online (Sandbox Code Playgroud)

进入C#数组.我收到错误"没有为'System.Array'类型定义无参数构造函数." 我从数据库中提取JSON,然后我想反序列化它以便我可以访问这些值并使用用户传入的任何内容更新数据库中的另一个字段.这只是我尝试的一个例子,我需要它是动态的,而不是静态的,因为数据库中包含的JSON字符串可以是变量.

我之前尝试过使用字典,但没有运气.所以我现在通过将其反序列化为数组来尝试不同的方法,然后我将从数组中填充字典.

这是我现在试图实现的方法......虽然我已经尝试了其他几个......

 IList<Array> ValueArray = new JavaScriptSerializer().Deserialize<IList<Array>>(this.Parameter.ValueList); 
 //this.Parameter.ValueList just contains my JSON string
Run Code Online (Sandbox Code Playgroud)

我想如果不创建我自己的课,我不能这样做?

当我尝试使用字典时,我尝试了这个

Dictionary<string, string> ValueList =
                JsonConvert.DeserializeObject<Dictionary<string, string>>(this.Parameter.ValueList);  
Run Code Online (Sandbox Code Playgroud)

但是收到了这个错误

"无法将当前的JSON数组(例如[1,2,3])反序列化为类型'System.Collections.Generic.Dictionary`2 [System.String,System.String]',因为该类型需要一个JSON对象(例如{"名称":"value"})要正确反序列化.要修复此错误,请将JSON更改为JSON对象(例如{"name":"value"})或将反序列化类型更改为数组或实现a的类型集合接口(例如ICollection,IList),如List,可以从JSON数组反序列化.JsonArrayAttribute也可以添加到类型中以强制它从JSON数组反序列化.路径'',第1行,位置1."

所以我开始尝试使用数组.

L.B*_*L.B 7

var list = new JavaScriptSerializer().Deserialize<List<KeyValue>>(json);

public class KeyValue
{
    public string key;
    public string value;
}
Run Code Online (Sandbox Code Playgroud)

或者只是KeyValue暂时使用

var dict = new JavaScriptSerializer().Deserialize<List<KeyValue>>(json)
                                     .ToDictionary(x => x.key, x => x.value);
Run Code Online (Sandbox Code Playgroud)

如果您打开使用Json.Net,可以直接将其转换为Dictionary

var dict = JsonConvert.DeserializeObject<JArray>(json)
                     .ToDictionary(x => (string)x["key"], x => (string)x["value"]);
Run Code Online (Sandbox Code Playgroud)