如何在没有额外库的情况下解析简单的json对象
本文关键字:情况下 简单 对象 json | 更新日期: 2023-09-27 18:14:05
这是我想解析的json对象,并把它变成一个字典:
[{"Id":100, "Name":"Rush", "Category":"Prog"},
{"Id":200, "Name":"Led Zeppellin", "Category":"Rock"},
{"Id":300, "Name":"Grumpy Lettuce", "Category":"Weird"}
]
我想从中获得Id和Name到Dictionary<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
命名空间