Wrong time while Deserialize json object - c#

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).

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.
}
}

Dictionary and object to web service content type string

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.

PayPal Pay Operation - error 81002

I'm not sure why this PayPal Pay operation is giving me this error even though I seem to have covered all the required fields:
Error Code: 81002 Severity: Error Message: Unspecified Method (Method Specified is not Supported)"
string postData = JsonConvert.SerializeObject(request);
value of postData:
"actionType=PAY
&currencyCode=USD
&cancelUrl=https%3a%2f%2fexample.com%2fcancel
&returnUrl=https%3a%2f%2fexample.com%2freturn
&requestenvelope.errorLanguage=en_US
&receiverList.receiver(0).email=recipientemail%40gmail.com
&receiverList.receiver(0).amount=0.05
&VERSION=94.0
&USER=bizemail-facilitator_api1.gmail.com
&PWD=xxxxx
&SIGNATURE=xxxxxxxxx"
Here's how I do the post:
SendRequest("https://api-3t.sandbox.paypal.com/nvp", postData);
public string SendRequest(string url, string postData)
{
var uri = new Uri(url);
var request = WebRequest.Create(uri);
var encoding = new UTF8Encoding();
var requestData = encoding.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.Timeout = (300*1000); //TODO: Move timeout to config
request.ContentLength = requestData.Length;
using (var stream = request.GetRequestStream()) {
stream.Write(requestData, 0, requestData.Length);
}
var response = request.GetResponse();
string result;
using (var reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII)) {
result = reader.ReadToEnd();
}
return result;
}
The method PAY doesn't exist on the NVP api. Full list of methods supported by that API is found here.
The PAY method, however, is defined in the Adaptive Payments API. Depending on your needs, you have two options:
Change the endpoint to https://svcs.paypal.com/AdaptivePayments/PAY and modify your values
Use another method, like DoDirectPayment, but I'm not sure it does what you want to.
I assume the value of postData is before you serialize it to a JSON string, instead of after as you say, since it is clearly not a JSON string.
If so, then it is already x-www-form-urlencoded, and you do not need to serialize it to a JSON string at all.
Or if you do after all, then change just this: request.ContentType = "application/json";

Simple REST request c# - error

I am trying write simple request to REST service.Follow to documentation from REST Service provider:
I should use in header Content-Type: application/json.
Response return in json format
For authorization proccess I have to send two headers one with APIKey and second with APISign
Controller PING in REST service to test code.
I use .net 2.0
string sha1String = APIKey + "/rest/ping" + APISecret;
string XRestApiSign = SHA1HashStringForUTF8String(sha1String);
string data = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(restServer);
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("X-Rest-ApiSign", XRestApiSign);
request.Headers.Add("X-Rest-ApiKey", APIKey);
request.ContentLength = data.Length;
StreamWriter requestWriter;
Stream webStream = request.GetRequestStream();
using (requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII)) ;
{
requestWriter.Write(data);
}
request.BeginGetResponse((x) =>
{
using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(x))
{
List<string> list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(response.GetResponseStream().ToString());
}
}, null);
I should get response string PONG but I get below message
Unexpected character encountered while parsing value: S. Path '', line 0, position 0
Is code OK ? Why I get this message?
This is mostly the case because the script that generates the JSON on the server side adds the byte order mark to the response.
In your case, however, you're trying to convert the stream to JSON, not the content of the stream. You need to read all text from the stream and deserialize the object from that. You need to call one of the methods on the stream that reads the content.
I modified my code with yours suggestion and it works. Now I have problem with send data :)
Subscription user1 = new Subscription
{
Email = "kubaIt#test.com.pl",
List = "xfct2bjcdv",
};
List<Subscription> user = new List<Subscription>();
user.Add(user1);
string json = JsonConvert.SerializeObject(user);
string data = json;
I added above. Other code is the same. I got error :The request was aborted: The request was canceled."
json = [{\"email\":\"kubaIt#test.com.pl\",\"list\":\"xfct2bjcdv\"}] //value from debuger

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

Categories