简体   繁体   English

c#处理字符串中的单双引号(json)

[英]c# handle single double quote in the string(json)

I'm using c# to handle JSON format to parse some data and I have encountered situation where i get this kind of JSON: 我正在使用c#来处理JSON格式来解析一些数据,我遇到过这种情况:我得到这种JSON:

"{"imperial":" 54 1/4" "}"

As you can see there's an inch symbol(double quote) after 你可以看到后面有一个英寸符号(双引号)

1/4

that leads me to an error. 这导致我出错。 how can i handle this double quote? 我怎么能处理这个双引号?

I'm using Newtonsoft.JSON to parse JSON and I tried many ways such as replacing " to ' which gives me the same error. 我正在使用Newtonsoft.JSON来解析JSON,我尝试了很多方法,比如替换“to”,这给了我同样的错误。

I thought about regex maybe? 我想过正则表达式可能吗? any suggestions? 有什么建议?

Thanks! 谢谢!

Code (for string like <NUMBER>/<NUMBER><DOUBLE QUOTE> ): 代码(对于字符串,如<NUMBER>/<NUMBER><DOUBLE QUOTE> ):

string json = "{\"imperial\":\" 54 1/4\" \"}";
string convertedJson = Regex.Replace(json, @"(\d+\/\d+)""", "$1\\\"");

var res = Newtonsoft.Json.JsonConvert.DeserializeObject(convertedJson);

Result (convertedJson): 结果(convertedJson):

{"imperial":" 54 1/4\" "}

You need to escape at least HTML characters (which include the quotes) before feeding the parser. 在提供解析器之前,您需要至少转义HTML字符(包括引号)。

If you have control of the generator of the JSON you are receiving and you are using also Newtonsoft, Newtonsoft.JSON's JsonWriter class has a property called StringEscapeHandling . 如果你控制了你正在接收的JSON的生成器,你也在使用Newtonsoft.JSON的JsonWriter类有一个名为StringEscapeHandling的属性。

This property can hold several values: Default , EscapeNonAscii and EscapeHTML (have a look at the doc ) 这个属性可以包含几个值: DefaultEscapeNonAsciiEscapeHTML (看一下doc

In your case, the EscapeHTML is the most interesting. 在您的情况下, EscapeHTML是最有趣的。 Quoting the doc: 引用文档:

EscapeHTML : HTML (<, >, &, ', ") and control characters (eg newline) are escaped. EscapeHTML :HTML(<,>,&,',“)和控制字符(例如换行符)被转义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM