How can I obtain a WebResponse in JSON without any whitespace in C#?

45 views Asked by At

I tried using WebRequest to call an API endpoint in C# and WebResponse to get the response. I am receiving JSON, but the JSON response is filled with a lot of whitespaces, which I'd like to get rid of.

I tried using formatting to get rid of whitespaces. Both Formatting.None and Formatting.Indented, yet both provide the same JSON output.

This is an example of my code:

System.Net.WebResponse resp = req.GetResponse();
string content;

using(System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream())) 
{
    content = sr.ReadToEnd();
}

dynamic parsedJson = JsonConvert.DeserializeObject(content);

content = JsonConvert.SerializeObject(parsedJson, Newtonsoft.Json.Formatting.None);

This form of JSON string is returned by the code above.

"{\n \t\"Success\": \"true\",\n \t\"Status\": 200,\n \t\"SuccessPnrs\": null,\n \t\"RepeatedPnrs\": [\n \t\t\"1184017\"\n \t]\n }"

Expected JSON shown here:

{"Success": "true","Status": 200,"SuccessPnrs": null,"phone": ["9568523624"]}
1

There are 1 answers

0
Gerhard Schmeusser On

If it's only about the \n \t characters I would simply use string.Replace("\t", "") and string.Replace("\n", "")