I’m using JSON to get a System.Net.WebResponse then reading the response into a StringBuilder before getting the result of the response by calling the StringBuilder.ToString() method. I can’t Parse such a respsone using Newtonsoft.Json.Linq.JObject.Parse(repsonse);
My problem is that the ToString() method is removing my ‘{‘ and ‘}’ characters because they get escaped unless matched with another ‘{‘. Even if I do a StringBuilder.Replace(“{“, “{{“) It doesn’t work because the final brackets escape the first brackets –> Example below
My code for getting the response is:
public static string GetResponseFromRequest(string url){
System.Net.WebRequest req = System.Net.WebRequest.Create(url);
System.Net.WebResponse res = req.GetResponse();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
byte[] read = new byte[256];
int count = res.GetResponseStream().Read(read, 0, 256);
while (count > 0)
{
sb.Append(System.Text.ASCIIEncoding.ASCII.GetString(read));
count = res.GetResponseStream().Read(read, 0, 256);
}
res.GetResponseStream().Close();
res.Close();
return sb.ToString();
}
Here is a sample of what my response looks like:
{{
"id" : "myID",
"Name" : "MyDisplayName",
"description" : "A, MyDescription",
}"hasOverview" : true,
"hasDescription" : true,
}
AFTER StringBuilder.ToString is called it looks like this:
"{
"id" : "myID",
"Name" : "MyDisplayName",
"description" : "A, MyDescription",
}"hasOverview" : true,
"hasDescription" : true,
"
If I call StringBuilder.Replace(“{“, “{{“) and StringBuilder.Replace(“}”, “}}”) I get:
"{{
"id" : "myID",
"Name" : "MyDisplayName",
"description" : "A, MyDescription",
}}"hasOverview" : true,
"hasDescription" : true,
"
I need a way to tell ToString() to return a literal representation of what the string builder is holding so it doesn’t take special characters into account. If possible just the ‘{‘ and ‘}’ characters in particular.
I disproved your original assumption by doing the following:
So with that out of the way, I think the problem is that you are trying to convert the text 256 bytes at a time, and mangling characters in the process. There are classes in the framework designed for the task you are attempting to accomplish, namely reading text from a Stream. Try this instead:
I tested this using the following method and the result looks OK:
EDIT:
Or better yet,