c#将字符串转换为JSON错误
本文关键字:JSON 错误 转换 字符串 | 更新日期: 2023-09-27 18:07: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标记添加到字段时,我遇到了问题。我想使用一个字体awesome图标旁边的名称,以表明这样的状态:
<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格式不正确。我错过了什么,或者HTML标记不能在JSON结构中使用?
问题是您正在生成一个无效的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();
尽管如此,您不应该在数据中添加标记。数据就是数据,仅此而已。如果您想要影响它的显示方式,则应该将该标记添加到视图中。