C # handle single double quote in string (json)

I am using C # to handle JSON format to parse some data, and I ran into a situation where I receive a JSON like this:

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

      

As you can see there is an inch (double quote) character after

1/4

      

which leads me to an error. how can i deal with this double quote?

I am using Newtonsoft.JSON to parse JSON and I have tried many ways such as replacing "with" which gives me the same error.

I was thinking about regex? any suggestions?

Thank!

+3


source to share


2 answers


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 (convertJson):

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

      

+2


source


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

If you have control over the JSON generator you get, and you use Newtonsoft as well, the Newtonsoft.JSON class JsonWriter

has a property StringEscapeHandling

.

This property can have multiple values: Default

, EscapeNonAscii

and EscapeHTML

(see doc all )



In your case, the most interesting is EscapeHTML

. Quoting the doc:

EscapeHTML

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

0


source







All Articles