I'm working on a webService app for the first time. I have an http api that I am using to get the list of URLs to download Sample.xml files. I have created an object class that contains the list of urls and I am trying to DeSerialize the jsonString directly into the List of URL. Any idea why DeserializeObject method is not working?
Here's my Code:
public class StoreGetXmlUrl
{
public bool Flag{ get; set; }
public List<String> Urls { get; set; }
public string ErrorMessage { get; set; }
}
public static List<String> CheckForNewXmlFile(string storeKey)
{
StoreGetXmlUrl result = new StoreGetXmlUrl();
result.Status = true;
_logger.Info($"Fetching new file URL for storekey:{storeKey}");
try
{
var request = (HttpWebRequest)WebRequest.Create("https://execute-api.us-west-2.com/default/param?=" + storeKey);
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
result.Urls = JsonConvert.DeserializeObject<List<String>>(responseString);
}
catch (WebException ex)
{
result.Status = false;
string errorMessage = ex.Message;
HttpWebResponse httpResponse = (HttpWebResponse)ex.Response;
using (WebResponse response = ex.Response)
using (Stream data = response.GetResponseStream())
using (StreamReader reader = new StreamReader(data))
{
errorMessage = reader.ReadToEnd();
}
#pragma warning disable 4014
_logger.Error($"Verification of store key failed with message: {errorMessage}");
#pragma warning restore 4014
result.ErrorMessage = errorMessage;
}
return result.Urls;
}
This is what the json response looks like:
responseString = "{\"urls\": [\"https://uswest2.abc.com/sample.xml\"]}"
result.Urls = JsonConvert.DeserializeObject<List<String>>(responseString);
The above line is trying to deserialize a string array from json below which is a JSON object that has a property named urls
that is actually a string array :
"{\"urls\": [\"https://uswest2.abc.com/sample.xml\"]}"
So you should be deserializing like this :
result = JsonConvert.DeserializeObject<StoreGetXmlUrl>(responseString);