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.
}
}
Related
I have Dictionary with values how to convert them to string of format application/json and application/x-www-form-urlencoded simplest standard way:
var values = new Dictionary<string, string>
{
{"id", "1"},
{"amount", "5"}
};
The same question regarding class object with the same fields:
class values
{
public String id { get; set; }
public string amount { get; set; }
}
simple way is using json.NET library in order to post the data. you can convert your object to application/json like this:
var jsonString = JsonConvert.SerializeObject(values);
then post it to your service like this:
private static T Call<T>(string url, string body)
{
var contentBytes = Encoding.UTF8.GetBytes(body);
var request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 60 * 1000;
request.ContentLength = contentBytes.Length;
request.Method = "POST";
request.ContentType = #"application/json";
using (var requestWritter = request.GetRequestStream())
requestWritter.Write(contentBytes, 0, (int)request.ContentLength);
var responseString = string.Empty;
var webResponse = (HttpWebResponse)request.GetResponse();
var responseStream = webResponse.GetResponseStream();
using (var reader = new StreamReader(responseStream))
responseString = reader.ReadToEnd();
return JsonConvert.DeserializeObject<T>(responseString);
}
It's not clear from your question if you want to manually serialize your dictionary or object and then send it using a custom way or if you would like to automatically serialize and send them to a web service.
The manual way:
Json
PM > Install-Package Newtonsoft.Json
Json.NET natively supports dictionary to Json object and, of course, object to json object serialization. You simply install it and than serialize using:
var jsonString = JsonConvert.SerializeObject(values); // values can be Dictionary<string, Anything> OR an object
Result:
{
"id": "1",
"amount", "5"
}
Form URL encoded
The cleanest way is to use the .NET built-in utility HttpUtility.ParseQueryString (which also encodes any non-ASCII character):
var nvc = HttpUtility.ParseQueryString("");
foreach(var item in values)
nvc.Add(item.Key, item.Value);
var urlEncodedString = nvc.ToString();
Result:
id=1&amount=5
Please note that there is no direct way to serialize an object into a Form URL encoded string without adding its members manually, e.g.:
nvc.Add(nameof(values.id), values.id);
nvc.Add(nameof(values.amount), values.amount);
The automatic way:
Everything is simpler if you just use HttpClient:
PM > Install-Package Microsoft.AspNet.WebApi.Client
Json
You may need to also use HttpClientExtensions extension methods for automatic Json serialization (without it you need to serialize it manually as shown above):
using (var client = new HttpClient())
{
// set any header here
var response = await client.PostAsJsonAsync("http://myurl", values); // values can be a dictionary or an object
var result = await response.Content.ReadAsAsync<MyResultClass>();
}
Form URL encoded
using (var client = new HttpClient())
{
using (var content = new FormUrlEncodedContent(values)) // this must be a dictionary or a IEnumerable<KeyValuePair<string, string>>
{
content.Headers.Clear();
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
var response = await client.PostAsync(url, content);
var result = await response.Content.ReadAsAsync<MyResultClass>();
}
}
This way you may serialize dictionaries directly. Again for objects you need to convert them manually as shown above.
I'm trying to use a web service to return an array to my GUI, but I don't know how to actually pull the array from the WebResponse.
This is a method in the GUI to make the call to the web service:
public static ArrayList getList()
{
String[] list;
WebRequest request = WebRequest.Create("localhost:8080/test");
WebResponse response = request.GetResponse();
list = ??? //<--What do I put here to actually access the returned array?
return response;
}
The answer to this would depend a lot on the format of the response. Is it JSON? XML?
If we assume that it is a JSON response representing a list of strings, you could do something like this:
using (var response = request.GetResponse() as HttpWebResponse)
{
Stream responseStream = response.GetResponseStream();
using (var reader = new StreamReader(responseStream))
{
// get the response as text
string responseText = reader.ReadToEnd();
// convert from text
List<string> results = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(responseText);
// do something with it
}
}
(this does require JSON.net)
I am deserializing List of class "pushNotification" using JavaScriptSerializer but I am not getting time values properly in result. However it is returned properly from the server side. I am using web http call to wcf to get list of this class. below is my code I get 6:00AM in "itemValue.ScheduledTime" however from service it was returned like 11 AM.
Datetime string returned from the server in JSON is "1425535200000+0500" and in datebase its "2015-03-05 11:00:00.000"
// Restful service URL
string url = "http://localhost:4567/ClientService.svc/GetPendingNotification";
string strResult = string.Empty;
// declare httpwebrequet wrt url defined above
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
// set method as post
webrequest.Method = "GET";
// set content type
// declare & read response from service
HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
// set utf8 encoding
// read response stream from response object
StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream());
// read string from stream data
strResult = loResponseStream.ReadToEnd();
var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<Dictionary<string, List<pushNotification>>>(strResult);
List<pushNotification> Notifications = new List<pushNotification>();
foreach (var itemValue in dict.Values.First())
{
Notifications.Add(new pushNotification { Message = itemValue.Message, toAndroid = itemValue.toAndroid , toiOS = itemValue.toiOS, ScheduledDate = Convert.ToDateTime(itemValue.ScheduledDate), ScheduledTime = Convert.ToDateTime(itemValue.ScheduledTime)});
}
JavaScriptSerializer doesn't understand timezone offset. Use DataContractJsonSerializer (https://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer%28v=vs.110%29.aspx) instead (you'll have to mark object you're serializing/properties with DataMember/DataContract attributes).
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
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 \