hollie3406 hollie3406 - 2 months ago 19
JSON Question

JSON Deserialize Error: The given key was not present in the dictionary

I'm trying to output JSON to a drop down list in a web form. I've managed to get this far:

WebClient client = new WebClient();
string getString = client.DownloadString("http://myfeed.com/app_feed.php");

JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic item = serializer.Deserialize<object>(getString);
string name = item["title"];

return name;


This brings back the feed ok but it runs into an error on the line:

string name = item["title"];


Bringing back this error:


Additional information: The given key was not present in the dictionary.


This is a sample of my feed:

{"apps":[{"title":"title1","description":"description1"},
{"title":"title2","description":"description2"},
{"title":"title3","description":"description3"}


So I thought that I was referencing the first title and I was planning to loop through them:

string name = item["title"];


But obviously not!
I have looked on Stackoverflow but I can't find an answer that I can apply to my own code.

Answer

title is inside another key apps and its an array so you should iterate it, I show you just select first one using index 0

string name = item["apps"][0]["title"];

you can access all by foreach

foreach (var ap in item["apps"])
{
    Console.WriteLine(ap["title"]);
}
Comments