Reputation: 3
I am not sure I framed the title properly, but I hope i get some assistance regardless. I am trying to consume an api but i keep getting "JsonSerializationException: Error converting value {null} to type 'System.Double". This happens when I try to deserialize in the line labeled as Error Line in the code just at the bottom
var response = JsonConvert.DeserializeObject<GetSalaryHistoryResponse>();
During the API call, I noticed about two fields with null values, which could be what is triggering the error
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx);
client.DefaultRequestHeaders.Add("API_KEY", "xxxxxxxxxxxxxxxxxxx");
client.DefaultRequestHeaders.Add("REQUEST_ID", "xxxxxxxx");
client.DefaultRequestHeaders.Add("MERCHANT_ID", "xxxxxxxx");
client.DefaultRequestHeaders.TryAddWithoutValidation("AUTHORIZATION", "ConsumerKey=Q1dHREVNTzEyMzR8Q1dHREVNTw==,ConsumerToken=c5e8db0cbca54593e54f6702778d1ea129463d5555166cd1d0c46416495df82483a08c30fdd1e9fa39ceeea9bc6d8da9ba892ff3c3f326d537bc06bf8ef3ece7");
string vv = request.ToJson();
var content = new StringContent(request.ToJson(), System.Text.Encoding.UTF8, "application/json");
var responseTask = client.PostAsync("provideCustomerDetails", content);
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsStringAsync();
readTask.Wait();
var a = readTask.Result.ToString();
***Error Line:>* ** var response = JsonConvert.DeserializeObject<GetSalaryHistoryResponse>(readTask.Result);
return response ;
}
}
I saw a hint to use the code snippet below, I also replaced attributesObject
with the class property and still get the error. I can't seem to figure out how to do this. i just want to be able to send the value of the Deserialization as a return value and use it elsewhere, can anyone help ?
var json = JsonConvert.SerializeObject(
attributesObject,
Formatting.None,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
Upvotes: 0
Views: 69
Reputation: 196
do not use .Result, or .Wait method if you don't want to use async/await in the method. Use .GetAwaiter().GetResult() in this case. I could imagine your method similar to this:
var response = client.PostAsync("provideCustomerDetails", content).GetAwaiter().GetResult();
if (response.IsSuccessStatusCode)
{
var content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
var deserialized = JsonConvert.DeserializeObject<DesiredTypeHere>(content, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
return deserialized;
}
Upvotes: -1