How to Remove Back Slashes from JSON Response in C#? - c#

I have written a webservice which converts the XML Response of a TP-Open Service into JSON format. I am new to WCF and writing Webservice.
But the converted JSON format displays as follow.
"{ \"data\": { \"current_condition\": [ {\"cloudcover\": \"25\", \"humidity\": \"48\", \"observation_time..
How to Remove these back slashes \ and my code so far.
public string checkweather(string q, string num_of_day)
{
HttpWebRequest request=..;
...
string Url = string.Format("http://free.worldweatheronline.com/feed/weather.ashx?q={0}&format={1}&num_of_days={2}&key={3}", q, format, num_of_days, key);
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(Url);
Request.Method = "GET";
using (HttpWebResponse response = (HttpWebResponse)Request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
var result2=reader.ReadToEnd();
}}}
return result2;
}
Please inform me if you need more information.

I think that your JSON is fine, the backslashes are escaping the quotations, which people have said. The following code shows some valid XML -> Json converting. (Using Json.NET)
const string xml = "<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>";
XmlDocument node = new XmlDocument();
node.LoadXml(xml);
string json = JsonConvert.SerializeXmlNode(node);
If you view in debug mode, you will see the backslashes, but the output is valid Json.
Output
{"note":{"to":"Tove","from":"Jani","heading":"Reminder","body":"Don't forget me this weekend!"}}

Are you sure there are backslashes in your string? It looks like me they are the escape characters because there are " characters in your string.

str = JToken.Parse(your string).ToString();

rest service time: System.Net.WebUtility.HtmlEncode(JsonString);
response time: System.Net.WebUtility.HtmlDecode(JsonString);
if your decoded code contains this string \\" then please replace \\ to \

Related

Read json object and find value in it

I have the following GET request:
string url = #"http://api.flexianalysis.com/services/flexianalysisservice.svc/TechnicalAnalysisByCategory?clientid=___&category=forex&key=____";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
rawJson = new StreamReader(response.GetResponseStream()).ReadToEnd();
//html = reader.ReadToEnd();
}
This is an example of the JSON:
[{"ID":133739,"TickerID":23,"CategoryID":3,"ClientID":5044,"TickerDateTime":"2017-11-06T12:57:19.267","TickerTitle":"AUD/USD Intraday: key resistance at 0.7670.\r\n","Category":"Forex","TradePairName":"AUD/USD","Ticker":"AUD","TrendType":"THE upside prevails","Status":"Enabled","TrendValue1":"+1","PivotValue":0.767,"OurPreference":"v: short positions below 0.7670 with targets at 0.7635 & 0.7615 in extension.\r\n","AlternateScenario":"o: above 0.7670 look for further upside with 0.7695 & 0.7715 as targets.\r\n","Comments":" as long as 0.7670 is resistance, look for choppy price action with a bearish bias.\r\n","S1":0.7635,"S2":0.7615,"S3":0.7595,"R1":0.767,"R2":0.7695,"R3":0.7715,"Entry":0.0,"Stop":0.0,"T1":0.0,"T2":0.0},{"ID":133738,"TickerID":193,"CategoryID":3,"ClientID":5044,"TickerDateTime":"2017-11-06T12:55:54.33","TickerTitle":"Dollar Index‏ (ICE) Intraday: bullish bias above 94.8000.\r\n","Category":"Forex","TradePairName":"Dollar Index (ICE)","Ticker":"DXA","TrendType":"THE upside prevails","Status":"Enabled","TrendValue1":"+1""PivotValue":94.8,"OurPreference":": long positions above 94.8000 with targets at 95.1500 & 95.3000 in extension.\r\n","AlternateScenario":"below 94.8000 look for further downside with 94.6500 & 94.4500 as targets.\r\n","Comments":": the RSI lacks downward momentum.","S1":94.8,"S2":94.65,"S3":94.45,"R1":95.15,"R2":95.3,"R3":95.45,"Entry":0.0,"Stop":0.0,"T1":0.0,"T2":0.0}]
Then i am trying to parse it to JSON and remove the 'd' at the beginning:
var json = JObject.Parse(rawJson);
var filter = json["d"];
var fff = filter["ID"];//Get the error here
Now I want to read the ID but for some reason it gives an error that it can't access child node.
Any idea why?
I think you need to check a few of your assumptions and try some break points.
Looking at the JSON returned by that API it looks like it's poorly formed and you are actually receiving a JSON array as a string:
{"d":"[{\"ID\":133739,\"TickerID\":23,\"CategoryID\":3,...}},
{\"ID\":133740,\"TickerID\":23,\"CategoryID\":3,...}},
[...]}]"}
Thus to parse it you'll first need to grab the value from the d parameter, and then parse that into an array:
// Get the response from the server
using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
{
// Pass the response into a stream reader
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
// Grab the JSON response as a string
string rawJson = reader.ReadToEnd();
// Parse the string into a JObject
var json = JObject.Parse(rawJson);
// Get the JToken representing the ASP.NET "d" parameter
var d = json.GetValue("d");
// Parse the string value of the object into a jArray
var jArray = JArray.Parse(d.ToString());
// At this point you can start looking for the items.
}
}

Handling escape characters in JSON response in C#

I have a rather simple issue that for some reason I can find a help for using SO and Google.
I am receiving a JSON reply that looks like this:
"{
\"data\": [
{
\"type\": \"gif\",
\"id\": \"FiGiRei2ICzzG\",
\"url\": \"http: //giphy.com/gifs/funny-cat-FiGiRei2ICzzG\",
\"bitly_gif_url\": \"http: //gph.is/1fIdLOl\",
\"bitly_url\": \"http: //gph.is/1fIdLOl\",
\"embed_url\": \"http: //giphy.com/embed/FiGiRei2ICzzG\",
\"username\": \"\",
\"source\": \"http: //tumblr.com\", etc........
So it's a standard JSON but with \ escape characters sprinkled in.
Now those escape characters I am trying to remove to parse data from the JSON.
Tried the .replace of the string and some other solutions, but for some reason I stay with the escape characters..
Thanks!!
This is the code I used to do the request
public static void GetRequest()
{
string sFullURL = "http://api.giphy.com/v1/gifs/search?q=";
string sSearchTerm = "funny+cat";
string sContent;
string sAPIKey = "&api_key=dc6zaTOxFJmzC";
string sLimit = "&limit=1";
string sFullRequest = "http://api.giphy.com/v1/gifs/search?q=funny+cat&api_key=dc6zaTOxFJmzC";
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format(sFullURL + sSearchTerm + sAPIKey + sLimit));
WebReq.Method = "GET";
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
System.Diagnostics.Debug.WriteLine(WebResp.StatusCode);
System.Diagnostics.Debug.WriteLine(WebResp.Server);
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
sContent = _Answer.ReadToEnd();
sContent = Regex.Replace(sContent, #"\\", "");
}
Looks like you're getting confused by the value in the debugger. The debugger windows shows an escaped version of the string.
You can click on the little magnification icon to open the string in a "text visualizer" to see the actual value of the string.
You're trying to escape the \ character twice using regular escaping ("\\") and verbatim strings (#"string").
Try
sContent = Regex.Replace(sContent, #"\", "");

Troubles read encrypted string which get from Web Request using StreamReader

So basically I want to get json string from specific url, and this json string is encrypted become a .txt file. All I want to do is get the encrypted string and decrypt it inside my application.
Here is my HttpWebRequest code to get the response string:
public string GetResponse(url)
{
string responseString = "";
HttpWebRequest webRequest = HttpWebRequest.Create(url) as HttpWebRequest;
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseString = reader.ReadToEnd();
}
return responseString;
}
But what I get from the response is actually an unreadable string (only "O")
I already try to convert it to byte array before convert it to Base64 string, but still, the response string is not right.
Thanks for the help.
Unfortunately, i didnt realize that the response string actually includes added character "/0" which i have to remove it first, then i able to decrypt the string.
Thank you very much.

Moving from standard .NET rest to RestSharp

For the most part, I have managed quite quickly to move my code from standard .NET code to using RestSharp. This has been simple enough for GET processes, but I'm stumped for POST processes
Consider the following
var request = System.Net.WebRequest.Create("https://mytestserver.com/api/usr") as System.Net.HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json;version=1";
request.Headers.Add("Content-Type", "application/json;version=1");
request.Headers.Add("Accepts", "application/json;version=1");
request.Headers.Add("Authorize", "key {key}");
using (var writer = new System.IO.StreamWriter(request.GetRequestStream())) {
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes("{\n \"firstName\": \"Dan\",\n \"lastName\": \"Eccles\",\n \"preferredNumber\": 1,\n \"email\" : \"testuser#example.com\",\n \"password\": \"you cant get the wood\"\n}");
request.ContentLength = byteArray.Length;
writer.Write(byteArray);
writer.Close();
}
string responseContent;
using (var response = request.GetResponse() as System.Net.HttpWebResponse) {
using (var reader = new System.IO.StreamReader(response.GetResponseStream())) {
responseContent = reader.ReadToEnd();
}
This is fairly straight forward to move across, except for the serialisation code. Is there a particular way this has to be done for RestSharp? I've tried creating an object and using
var json = JsonConvert.SerializeObject(user);
restRequest.RequestFormat = DataFormat.Json;
restRequest.AddBody(json);
but the server still comes back with an error.
I'm also currently using JSON.NET for deserialization to an error object when the user passes in bad data. Is there a way I can deserialize to error object based on a single string using RestSharp?
You're close, but you don't need to worry about serialization with RestSharp.
var request = new RestRequest(...);
request.RequestFormat = DataFormat.Json;
request.AddBody(user); // user is of type User (NOT string)
By telling it that the format is JSON, then passing your already-serialized-as-JSON string, RestSharp is actually encoding it again as a string.
So you pass the string: {"firstName":"foo"} and it actually gets sent to the server as a JSON string object: "{\"firstName\":\"foo\"}" (note how your JSON is escaped as a string literal), which is why it's failing.
Note you can also use an anonymous object for the request:
var request = new RestRequest(...);
request.RequestFormat = DataFormat.Json;
request.AddBody(new{
firstName = "Dan",
lastName = "Eccles",
preferredNumber = 1,
// etc..
});
You use the same typed objects with the response (eg, RestSharp deserializes for you):
var response = client.Execute<UserResponse>(request);
// if successful, response.Data is of type UserResponse

Invalid Data HttpWebResponse from HttpWebRequest C#

I am trying to load an HttpWebResponse into an XmlDocument and am getting the exception "Data at the root level is invalid. Line 1, position 1". If I output the response to the Console I get "system.net.connectstream". The credentials don't seem to be my problem because if I enter an incorrect password my exception changes to the 404 error. Here is my code...
string username = "username";
string password = "password";
string url = "https://myurl.com";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Credentials = new NetworkCredential(username, password);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
XmlDocument xmlDoc = new XmlDocument();
Console.WriteLine(response.GetResponseStream());
xmlDoc.Load(response.GetResponseStream());
Thanks!
Calling ToString on GetResponseStream() isn't going to do much for you - Stream.ToString isn't overridden.
I suggest you use something like this for debugging::
// Prefer casting over "as" unless you're going to check it...
using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
// For diagnostics, let's assume UTF-8
using (StreamReader reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}
Then replace the middle section (with StreamReader) with the XmlDocument.Load call.
I suspect you'll see that it's basically invalid XML, but the above should show you what it really is.
EDIT: Your comment shows the data as:
{"messages":{"message":"1 Device(s) returned."},"devices":{"device":
{"#id":"00","uuid":"00000000","phonenumber":"000‌​000",
"user name":"0000","name":"Guy,Somebody","platform":"platform","os":"III",
"version":"1‌​.1.1"}},"appName":"someApp"}
That's JSON. It's not XML. Don't try to load it as XML. You have two options:
Change what you're requesting so that you get an XML response back, if the server supports it
Parse it as JSON (e.g. with Json.NET) instead of as XML.

Categories