简体   繁体   中英

How to parse simple json object without extra libraries in c#?

This is the json object I want to parse and turn into a Dictionary:

[{"Id":100, "Name":"Rush", "Category":"Prog"},
 {"Id":200, "Name":"Led Zeppellin", "Category":"Rock"},
 {"Id":300, "Name":"Grumpy Lettuce", "Category":"Weird"}
]

I'd like to get the Id and Name from that into a Dictionary<int, string>()

Thanks!

There is rudimentary JSON support in the .NET framework: http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx

However, I would recommend using a specialized library, JSON.NET: like 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());
  }

Note: you will need to reference System.Web.Extensions.dll and import the System.Web.Script.Serialization namespace

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM