【发布时间】:2021-04-26 23:48:47
【问题描述】:
我是第一次开发 webService 应用程序。我有一个 http api,用于获取下载 Sample.xml 文件的 URL 列表。我创建了一个包含 url 列表的对象类,我试图将 jsonString 直接反序列化到 URL 列表中。知道为什么 DeserializeObject 方法不起作用吗?
这是我的代码:
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;
}
这是 json 响应的样子:
responseString = "{\"urls\": [\"https://uswest2.abc.com/sample.xml\"]}"
【问题讨论】:
标签: c# json api httprequest json-deserialization