如何使用JSON.Net阅读JSON和输出HTML? [英] How to use JSON.Net to read JSON and output HTML?

查看:99
本文介绍了如何使用JSON.Net阅读JSON和输出HTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么可以使用JSON.Net和环路通过以下JSON输出一个HTML图像标记(一个字符串)的照片每一个成员对象?

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?

我的目标是阅读以下JSON输出字符串:

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存储在外部文件photos.json

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"
        }
    }
}

我已经开始使用类似code怎么在这里显示:的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.

我想通过照片对象,阅读性能和添加HTML到我的字符串为每张照片的每一个成员循环。

I want to loop through each member of the photos object, read the properties and add html to my string for each photo.

到目前为止,我已经试过这里显示的例子:的 http://james.newtonking.com/json/help/index.html?topic=html/QueryJson.htm
但是,我不能让他们内部的工作,一次为每个循环。

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.

推荐答案

下面是你如何可以走动你的 JObject 来提取所需的信息。

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());

输出:

<img src='/images/foo.jpg' alt='Hello World!' />
<img src='/images/bar.jpg' alt='Another Photo' />

这篇关于如何使用JSON.Net阅读JSON和输出HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆