How to use JSON.Net to read JSON and output HTML?
asp.net, c#, json.net, linq
Solution
Here is how you can "walk around" your `JObject` to extract the information you need.
string json = @"
{
""photos"": {
""photo1"": {
""src"": ""/images/foo.jpg"",
""alt"": ""Hello World!""
},
""photo2"": {
""src"": ""/images/bar.jpg"",
""alt"": ""Another Photo""
}
}
}";
StringBuilder sb = new StringBuilder();
JObject o = JObject.Parse(json);
foreach (JProperty prop in o["photos"].Children<JProperty>())
{
JObject photo = (JObject)prop.Value;
sb.AppendFormat("<img src='{0}' alt='{1}' />\r\n",
photo["src"], photo["alt"]);
}
Console.WriteLine(sb.ToString());
Output:
<img src='/images/foo.jpg' alt='Hello World!' />
<img src='/images/bar.jpg' alt='Another Photo' />
Problem
How can I use JSON.Net and loop through the following JSON to output one HTML image tag (a string) for each member of the "photos" object? My goal is to read the below JSON and output this string: ``` "<img src='/images/foo.jpg' alt='Hello World!'><img src='/images/bar.jpg' alt='Another Photo' />" ``` JSON is stored in external file "photos.json" ``` { "photos": { "photo1": { "src": "/images/foo.jpg", "alt": "Hello World!" }, "photo2": { "src": "/images/bar.jpg", "alt": "Another Photo" } } } ``` I've started with code similar to what's shown here: http://www.hanselman.com/blog/NuGetPackageOfTheWeek4DeserializingJSONWithJsonNET.aspx ``` var client = new WebClient(); client.Headers.Add("User-Agent", "Nobody"); var response = client.DownloadString(new Uri("http://www.example.com/photos.json")); JObject o = JObject.Parse(response);' //Now o is an object I can walk around... ``` But, I haven't found a way to "walk around o" as shown in the example. I want to loop through each member of the photos object, read the properties and add html to my string for each photo. So far, I've tried the examples shown here: http://james.newtonking.com/json/help/index.html?topic=html/QueryJson.htm But, I cannot make them work once inside a for each loop.