【问题标题】:C# Convert string to JSON errorsC# 将字符串转换为 JSON 错误
【发布时间】:2016-09-16 18:27:14
【问题描述】:

我为 dataTables 插件构建了一个公共类的一部分。

构建数据结构的代码是:

var response = "{ \"data\": [";
    response = response + "[";
    response = response + "\"Clark, Keith\",";
    response = response + "\"Corporate\",";
    response = response + "\"XXX-XXX-XXXX\",";
    response = response + "\"XXX-XXX-XXXX\",";
    response = response + "\"XXXX@XXXX.com\"";
    response = response + "],";
    response = response + "[";
    response = response + "\"Clark, Keith\",";
    response = response + "\"Corporate\",";
    response = response + "\"YYY-YYY-YYYY\",";
    response = response + "\"YYY-YYY-YYYY\",";
    response = response + "\"YYYY@XXXX.com\"";
    response = response + "]";
    response = response + "] }";

return response;

这运行良好并按预期创建表。我遇到问题的地方是当我尝试将 HTML 标记添加到字段时。我想在名称旁边使用一个很棒的字体图标来表示这样的状态:

<i class="fa fa-arrow-up" style="color: #00ff00;" aria-hidden="true">

我已尝试将我的代码修改为:

response = response + "\"<i class=\"\"fa fa-arrow-up\"\" style=\"\"color: #00ff00;\"\" aria-hidden=\"\"true\"\">Clark, Keith\",";

但现在我收到 JSON 格式不正确的错误消息。是我遗漏了什么还是不能在 JSON 结构中使用 HTML 标记?

【问题讨论】:

  • 您没有遗漏任何内容,html 标记不是有效的 JSON。 JSON 字符串必须完全独立。
  • 发布包含新内容的 json。您不会在最终关闭后尝试添加它吗?
  • @JonathonChase 里面有html没有错,html只是静态文本,这正是JSON擅长的。
  • 这里有个提示,不要手动构建json字符串。
  • @Jeff Mercado 如果不是手工制作,当它包含有条件的 HTML 标记时,您建议如何构建它?

标签: c# html json


【解决方案1】:

问题是您生成的 json 字符串文字无效。

"<i class=""fa fa-arrow-up"" style=""color: #00ff00;"" aria-hidden=""true"">Clark, Keith",

引号使用文字反斜杠转义,而不是加倍。

您将不得不这样做:

"\"<i class=\\\"fa fa-arrow-up\\\" style=\\\"color: #00ff00;\\\" aria-hidden=\\\"true\\\">Clark, Keith\","

这说明了为什么您不应该生成这样的字符串。有一些工具可以为您做到这一点,并且安全地使用它们。 Json.net 可以轻松解决这个问题。

var markup = "<i class=\"fa fa-arrow-up\" style=\"color: #00ff00;\" aria-hidden=\"true\">";
var response = new JObject
{
    ["data"] = new JArray
    {
        new JArray
        {
            markup + "Clark, Keith",
            "Corporate",
            "XXX-XXX-XXXX",
            "XXX-XXX-XXXX",
            "XXXX@XXXX.com",
        },
        new JArray
        {
            markup + "Clark, Keith",
            "Corporate",
            "YYY-YYY-YYYY",
            "YYY-YYY-YYYY",
            "YYYY@XXXX.com",
        },
    }
};
return response.ToString();

话虽如此,您不应该在数据中添加标记。数据就是数据,仅此而已。如果您想影响它的显示方式,则应将该标记添加到您的视图中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多