Reputation: 105
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!
Upvotes: 3
Views: 3503
Reputation: 2761
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\" "}
Upvotes: 2
Reputation: 2107
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 (e.g. newline) are escaped.
Upvotes: 0