简体   繁体   中英

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:

"{"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.

I thought about regex maybe? any suggestions?

Thanks!

Code (for string like <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):

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

You need to escape at least HTML characters (which include the quotes) before feeding the parser.

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 .

This property can hold several values: Default , EscapeNonAscii and EscapeHTML (have a look at the doc )

In your case, the EscapeHTML is the most interesting. Quoting the doc:

EscapeHTML : HTML (<, >, &, ', ") and control characters (eg newline) are escaped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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