将JSON反序列化为KeyValue对的列表
问题描述:
我有以下json:
[
{
"key":"key1",
"value":"val1"
},
{
"key":"key2",
"value":"val2"
}
]
如何将其反序列化为NameValuePair<string, string>
的列表/数组?
How can I deserialize it into an list/array of NameValuePair<string, string>
?
示例:
var json = "[{\"key\":\"key1\",\"value\":\"val1\"},{\"key\":\"key2\",\"value\":\"val2\"}]";
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<List<KeyValuePair<string,string>>>(json);
上面的代码运行,但是列表中的数据为null
.我可以将数组提取到List<Object>
.
The above code runs but the data inside the list is null
. I can extract the array into an List<Object>
though.
答
首先,您不应该使用JavaScriptSerializer
,Microsoft甚至明确表示
First off, you should not be using JavaScriptSerializer
, Microsoft even explicitly says that in the JavaScriptSerializer docs.
要在Json.NET中反序列化对象,语法非常相似:
To deserialize an object in Json.NET the syntax is very similar:
var json = "[{\"key\":\"key1\",\"value\":\"val1\"},{\"key\":\"key2\",\"value\":\"val2\"}]";
var result = JsonConvert.DeserializeObject<List<KeyValuePair<string,string>>>(json);
小提琴此处