0

这是我要解析并变成字典的 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>()

谢谢!

4

2 回答 2

1

.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

于 2013-05-17T23:13:47.653 回答
0
  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命名空间

于 2013-05-17T23:41:11.943 回答