0

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!

2
  • 2
    use JavaScriptSerializer.Deserialize - msdn.microsoft.com/en-us/library/ee191864.aspx Commented May 17, 2013 at 22:47
  • I had a similar question here. But this does require the JSON.Net library. Commented May 17, 2013 at 22:47

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

+1 and converting to Dictionary can be done using ToDictionary() extension : msdn.microsoft.com/en-us/library/…
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());
  }

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.