【问题标题】:HTML string as a JSON output using C#使用 C# 将 HTML 字符串作为 JSON 输出
【发布时间】:2018-06-08 16:59:13
【问题描述】:

使用 C# 将 HTML 字符串作为 JSON 输出。

我想用 ' 替换 HTML 包装器 之间的每个实例,同时转换为 JSON。同时,如果它有带有 " 引号的文本,那么它不应该被替换为 ' 引号。例如。 "since the 1500s"

代码 - 将所有 " 替换为 ' 引号

public string Content
{
    get
    {
       return _content;
    }
    set
    {
       if (value != null)
       {
           this._content = this._content.Replace("\"", "'");     
       }
     }
}

我正在从我的视图中获取这种形式的字符串。

E.g.  model.Content = "<p> Lorem Ipsum is simply dummy text of the printing <span id= "#" ids= "#" display= "inline" ></ span > and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever "since the 1500s".<br></p>";

我正在使用 JsonConvert.SerializeObject

string output = JsonConvert.SerializeObject(model, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });

预期字符串 - HTML 标记中的所有双引号应转换为单引号,但文本引号应与使用 C# 时一样

 "content": "<p><b>Lorem Ipsum</b> is simply dummy <i>text </i>of the printing&nbsp;<span id='#' ids='#' display='inline'></span> and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever \"since the 1500s\".</p>",

【问题讨论】:

  • 请您提供更多信息。例如,为什么双引号应该变成单引号?您如何将其转换为 JSON 等?
  • 是c#返回这个输出的方法吗?请提供更多信息
  • 您使用的是 JSON.NET 还是 JavaScriptSerializer 或任何其他 Serializer?
  • @Jack 用代码更新你的问题会很有用,否则那只是一团糟。 ps 也尝试一下格式化它
  • 更新问题

标签: c# html json


【解决方案1】:

我想你想用 ' 替换 " 的每个实例,即在 之间。

因此,您在字符串中查找每个 ",在后面查找 。正则表达式如下所示:

(?<=\<[^<>]*)"(?=[^><]*\>)

所以你可以使用

outputString = Regex.Replace(inputString, "(?<=\\<[^<>]*)\"(?=[^><]*\\>)", "'");

然后你想在你的字符串中转义其他 "。为此你可以使用

outputString = outputString.Replace(@"""", @"\""");

outputString = outputString.Replace("\"", "\\\"");

我创建了一个控制台应用程序来测试这个,

 Console.WriteLine("Enter The String : ");
 string input = Console.ReadLine();          
 string pattern = "(?<=\\<[^<>]*)\"(?=[^><]*\\>)";
 string output = Regex.Replace(input, pattern, "'");
 output = output.Replace(@"""", @"\""");
 Console.WriteLine(output);
 Console.ReadKey();

输入字符串是您提供的字符串,然后输出将是,

<p> Lorem Ipsum is simply dummy text of the printing <span id= '#' ids= '#' display= 'inline' ></ span > and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever \"since the 1500s\".<br></p>

【讨论】:

  • 是的,你是对的,但是这个表达式不起作用
  • 我使用示例控制台应用程序更新了答案。检查
【解决方案2】:

最好将所有的 double(") 替换为 (\")。这样,您可以将双引号存储为字符串的一部分。 敌人的例子:

string storeValue = "Subash \"Kharel\"";

【讨论】:

    猜你喜欢
    • 2017-06-12
    • 2017-01-22
    • 2015-12-08
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 2015-04-26
    • 2014-06-24
    • 1970-01-01
    相关资源
    最近更新 更多