Deserialize json to list of KeyValue pairs [duplicate]

孤人 提交于 2019-12-13 04:11:12

问题


I have the following json:

[
   {
      "key":"key1",
      "value":"val1"
   },
   {
      "key":"key2",
      "value":"val2"
   }
]

How can I deserialize it into an list/array of NameValuePair<string, string>?

Example:

var json = "[{\"key\":\"key1\",\"value\":\"val1\"},{\"key\":\"key2\",\"value\":\"val2\"}]";

var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<List<KeyValuePair<string,string>>>(json);

The above code runs but the data inside the list is null. I can extract the array into an List<Object> though.


回答1:


First off, you should not be using JavaScriptSerializer, Microsoft even explicitly says that in the JavaScriptSerializer docs.

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);

Fiddle here



来源:https://stackoverflow.com/questions/50279506/deserialize-json-to-list-of-keyvalue-pairs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!