WebApi响应反序列化为List <string>

时间:2015-12-28 13:27:23

标签: c# asp.net-web-api windows-runtime json.net deserialization

以下工作正常并且使用了很长时间。

Uri requestUri = new Uri("http://somewebsite.com/api/Images");
var client = new HttpClient();
var response = await client.GetAsync(requestUri);
StorageFolder folder = ApplicationData.Current.LocalFolder;

if (response.IsSuccessStatusCode)
{
    string responseBody = await response.Content.ReadAsStringAsync();
    List<string> myList = await Task.Factory.StartNew(() => JsonConvert.DeserializeObject<List<string>>(responseBody));

    // more logic here 
}

代码 await Task.Factory.StartNew(() => JsonConvert.DeserializeObject<List<string>>(responseBody)); 看起来不太可读,并且想知道是否有简化的等效代码。

您是否可以建议从来自网络Api的HTTP响应内容中获取List<string>的更好选择?

1 个答案:

答案 0 :(得分:0)

如果您不关心异步操作,我认为您可以这样做:

var responseBody = client.GetAsync(url).Result
    .Content.ReadAsStringAsync().Result;

var myList = JsonConvert.DeserializeObject<List<string>>(responseBody);
编辑:抱歉,省略了您的回复状态检查。我认为这样可行:

if (response.IsSuccessStatusCode)
{
    var responseBody = response.Content.ReadAsStringAsync().Result;
    var myList = JsonConvert.DeserializeObject<List<string>>(responseBody);
    // ...