user2921851
user2921851

Reputation: 990

WebApi response deserialization into List<string>

The following works fine and used it for quite a while.

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 
}

The code await Task.Factory.StartNew(() => JsonConvert.DeserializeObject<List<string>>(responseBody)); looks less readable and was wondering if there is a simplified equivalent.

Can you suggest a better alternative for getting List<string> from an HTTP Response Content coming from web Api?

Upvotes: 5

Views: 4045

Answers (1)

pixelmike
pixelmike

Reputation: 1983

If you don't care about the operation being async, I think you could do:

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

var myList = JsonConvert.DeserializeObject<List<string>>(responseBody);

EDIT: Sorry, that omits your response status check. I think this would work:

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

Upvotes: 3

Related Questions