Hello Techies. I hope you are doing great in your field.
Let's learn something new and get the solution of a very well-known issue while getting the JSON String as response from the API. But, what if you are trying to get the response from the API, and it contains the HTML content and multiple double quotes inside the string?
That's the same issue I was facing, and I have tried the different HTML decode functions, but that didn't work. So, I have to go with the custom functions and got the clean response after successful parsing.
Let's check what JSON String I was getting and what is the issue I was facing with the JSON String. Following is the JSON String Response I was getting.
{
"Link": "<a href="https: //www.c-sharpcorner.com/members/jay-pankhaniya">Jay Pankhania</a>",
"name": "<p>Jay Pankhania</p>",
"Description":"Hello Folks, My Name is "Jay Pankhaniya". Currently, Working as the JR. Software
Developer at Binary Republik- Ahmedabad. I have Completed B.E. In Computer
Engineering from Marwadi University",
"host": "c-sharp Corner",
}
Here, this JSON contains the HTML code inside the JSON and double quotes inside the description part. So, to resolve this issue, I have tried different httputility.HTMLDecode(“<any string>”). But, It was not working. So, let's check out the following function which is working for my solution to get the JSON Object.
private static string HtmlToPlainText(string JsonString) {
const string tagWhiteSpace = @ "(>|$)(\W|\n|\r)+<";
const string stripFormatting = @ "<[^>]*(>|$)";
const string lineBreak = @ "<(br|BR)\s{0,1}\/{0,1}>";
var lineBreakRegex = new Regex(lineBreak, RegexOptions.Multiline);
var stripFormattingRegex = new Regex(stripFormatting, RegexOptions.Multiline);
var tagWhiteSpaceRegex = new Regex(tagWhiteSpace, RegexOptions.Multiline);
var text = JsonString;
text = System.Net.WebUtility.HtmlDecode(text);
text = tagWhiteSpaceRegex.Replace(text, "><");
text = lineBreakRegex.Replace(text, Environment.NewLine);
text = stripFormattingRegex.Replace(text, string.Empty);
return text;
}
In the above function, let's check the code in short one by one without going into the deep,
- The first line will match the white space and line break between the angular braces.
- Second line will match the tags between the angular braces, even if the end tag is missing
- Third line will match the line break tag.
- The following line from 5 to 7 will create the Regex of the above lines.
- The following line from 10 to 13 will match the JSON String and remove the HTML content, and it gives the clean JSON string.

Join the conversation! Your thoughts help the community grow.