Reputation: 749
I'm a bit of a newbie when it comes to linq and I'm working on a site that parses a json feed using json.net. The problem that I'm having is that I need to be able to pull multiple fields from the json feed and use them for a foreach block. The documentation for json.net only shows how to pull just one field. I've done a few variations after checking out the linq documentation, but I've not found anything that works best. Here's what I've got so far:
WebResponse objResponse;
WebRequest objRequest = HttpWebRequest.Create(url);
objResponse = objRequest.GetResponse();
using (StreamReader reader = new StreamReader(objResponse.GetResponseStream()))
{
string json = reader.ReadToEnd();
JObject rss = JObject.Parse(json);
var postTitles =
from p in rss["feedArray"].Children()
select (string)p["item"],
//These are the fields I need to also query
//(string)p["title"], (string)p["message"];
//I've also tried this with console.write and labeling the field indicies for each pulled field
foreach (var item in postTitles)
{
lbl_slides.Text += "<div class='slide'><div class='slide_inner'><div class='slide_box'><div class='slide_content'></div><!-- slide content --></div><!-- slide box --></div><div class='rotator_photo'><img src='" + item + "' alt='' /></div><!-- rotator photo --></div><!-- slide -->";
}
}
Has anyone seen how to pull multiple fields from a json feed and use them as part of a foreach block (or something similar?
Upvotes: 2
Views: 381
Reputation: 129827
Couldn't you just reference the fields directly in your foreach loop, like this (below)? I'm not sure you really need the linq query here. (Note, I have cut out most of your html for this example for clarity. You'll need to adjust for your actual project, do appropriate HTML escaping, etc.)
foreach (var p in rss["feedArray"].Children())
{
lbl_slides.Text += string.Format(
"<img src='{0}' title='{1}'/><span>{2}</span>",
(string)p["item"],
(string)p["title"],
(string)p["message"]);
}
Same thing using linq would look like this:
var postTitles =
from p in rss["feedArray"].Children()
select new
{
Src = (string)p["item"],
Title = (string)p["title"],
Message = (string)p["message"],
}
foreach (var item in postTitles)
{
lbl_slides.Text += string.Format(
"<img src='{0}' title='{1}'/><span>{2}</span>",
item.Src, item.Title, item.Message);
}
Upvotes: 2