【问题标题】:How can I convert encoding in a JSON result to display quotation marks correctly in HTML如何将 JSON 结果中的编码转换为在 HTML 中正确显示引号
【发布时间】:2017-02-28 10:13:06
【问题描述】:

显示时我需要将“€”或\u00e2\u20ac\u0153 转换为引号。我正在使用 HTML Agility Pack 从外部网页获取元数据,以通过 ajax 显示链接预览并返回 json 结果。在 html 中显示时,我无法弄清楚如何转换回引号。

数据来自外部站点,尚未保存在我的数据库中。 HTML 和 ajax 标头都设置为 UTF-8。

我使用以下代码从 HTML Agility Pack 获取结果

var metaTags = document.DocumentNode.SelectNodes("//meta");
    if (metaTags != null)
        {
        foreach (var tag in metaTags)
            {
            if (tag.Attributes["property"] != null && 
            tag.Attributes["content"] != null 
            && tag.Attributes["property"].Value.ToLower() == "og:description")
                {
                OgDescription = tag.Attributes["content"].Value;
                //^^returning “

                //OgDescription = EncodeNonAsciiCharacters(OgDescription);
                //^^returning \u00e2\u20ac\u0153
                }
           }
       }

    var meta = new UrlPreviewDto(){
       OgDescription = OgDescription
    };

return Ok(meta);

我正在通过 ajax 调用 web api 并附加到 html 中的元素

         $.post(uri,
                { '': url,
                contentType : "text/html; charset=utf-8" }
            ).done(function (data) {
                            if (data.ogDescription != "") {
                //var ogDescription = JSON.parse('"' + data.ogDescription.replace(/\"/g, '\\"') + '"');
                $('.description').append(data.ogDescription);
            }

json 结果正在返回

{ "url": "http://www.realbusinessrescue.co.uk/news/business-rates-are-a-ticking-timebomb-for-small-companies", "description": "Business rates are effectively a “ticking time bomb†for small businesses throughout England", "title": "Business Rates Are A 'Ticking Timebomb\" For Small Companies", "ogDescription": "Business rates are effectively a “ticking time bomb†for small businesses throughout England" }

我显然想显示引号而不是编码字符。在 c# 代码或 jquery/javascript 中是否有一种简单的方法可以做到这一点?

提前感谢您的帮助。

【问题讨论】:

  • 当您使用 Agility Pack 加载文档时,您是否检查了页面的编码和/或将编码指定为 UTF-8?不确定,但如果源页面“不是”UTF-8,假设页面是 UTF-8 也可能会得到意外结果。
  • 我不是在查看页面源,其中有问题的响应来自它是 UTF-8。我确实注意到元数据中的引号比正常情况下更卷曲(因为需要更技术性的描述)

标签: c# asp.net json asp.net-web-api html-agility-pack


【解决方案1】:

如果您无法事先让 Json 看起来不错,您至少可以在事后使用 javascript 更正描述。

$('.description').append(data.ogDescription.replace(/“?/g, "\""));

【讨论】:

  • 这会很好,但我想我需要找到一个更强大的解决方案来处理所有编码字符而不仅仅是撇号。不过,谢谢您的意见。
猜你喜欢
  • 2016-11-21
  • 1970-01-01
  • 2015-05-12
  • 2021-11-21
  • 2019-12-07
  • 2018-05-09
  • 1970-01-01
  • 2015-12-12
  • 2021-07-27
相关资源
最近更新 更多