Question

I am trying to get some data from a web server. When I go via a browser I see a response like:

[ { "x": "1" ,"y" : "2" ,"z" : "3" } ] 

When I send a GET request the result comes back:

[ {\n\"x\": \"1\"\n,\"y\" : \"2\"\n,\"z\" : \"3\"\n\n}\n]\n"

The code I am using is basically:

// Create a request for the URL.
WebRequest request = WebRequest.Create(fullUrl);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();

Is there an easy way to get rid of the \n and the \ before the " , or do I have to do some regex/string manipulation on the response?

Thanks, Will

Was it helpful?

Solution

The '\' before the quotation marks is simply what you will see in the debugger and represents an escaped quotation mark - no problem as it is for display purposes only and will not be present as a character when performing string manipulations.

The '\n' character is a new-line character and this is actually there. If you do not want it in the string, you can remove it with the following:

responseFromServer = responseFromServer.Replace("\n", string.Empty);

OTHER TIPS

[ {\n\"x\": \"1\"\n,\"y\" : \"2\"\n,\"z\" : \"3\"\n\n}\n]\n"

is probably what you see in Visual Studio debugger. You don't need to get rid of anything. Also you could simplify your code a bit because all those undisposed resources in your sample could leak unmanaged handles:

using (var client = new WebClient())
{
    string responseFromServer = client.DownloadString(fullUrl);
}
[ {\n\"x\": \"1\"\n,\"y\" : \"2\"\n,\"z\" : \"3\"\n\n}\n]\n"

This is presentation of string by your IDE escaped as you would while using it in your code where \n Represents Line Break and \" if escaped quotation mark, browser also receives same string but it displays Newlines as space :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top