这是我要解析并变成字典的 json 对象:
[{"Id":100, "Name":"Rush", "Category":"Prog"},
{"Id":200, "Name":"Led Zeppellin", "Category":"Rock"},
{"Id":300, "Name":"Grumpy Lettuce", "Category":"Weird"}
]
我想从中获取 Id 和 NameDictionary<int, string>()
谢谢!
.NET 框架中有基本的 JSON 支持:http: //msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
但是,我建议使用专门的库 JSON.NET:例如http://james.newtonking.com/pages/json-net.aspx
void Main()
{
const string thatJsonYouWrote = @"[{""Id"":100, ""Name"":""Rush"", ""Category"":""Prog""}, {""Id"":200, ""Name"":""Led Zeppellin"", ""Category"":""Rock""}, {""Id"":300, ""Name"":""Grumpy Lettuce"", ""Category"":""Weird""}]";
IDictionary<int,string> thatThingYouWanted = ParseJsonExample(thatJsonYouWrote);
}
IDictionary<int,string> ParseJsonExample(string json)
{
object[] items = ((object[])new JavaScriptSerializer().DeserializeObject(json));
return items
.Cast<Dictionary<string,object>>()
.ToDictionary(_ => Convert.ToInt32(_["Id"]), _ => _["Name"].ToString());
}
注意:您需要引用System.Web.Extensions.dll
和导入System.Web.Script.Serialization
命名空间