Deserialize JSON to Array or List with HTTPClient .ReadAsAsync using .NET 4.0 Task pattern

前端 未结 3 2013
礼貌的吻别
礼貌的吻别 2020-12-07 13:10

I\'m trying to deserialize the JSON returned from http://api.usa.gov/jobs/search.json?query=nursing+jobs using the .NET 4.0 Task pattern. It returns this JSON

3条回答
  •  -上瘾入骨i
    2020-12-07 13:49

    The return type depends on the server, sometimes the response is indeed a JSON array but sent as text/plain

    Setting the accept headers in the request should get the correct type:

    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
    

    which can then be serialized to a JSON list or array. Thanks for the comment from @svick which made me curious that it should work.

    The Exception I got without configuring the accept headers was System.Net.Http.UnsupportedMediaTypeException.

    Following code is cleaner and should work (untested, but works in my case):

        var client = new HttpClient();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var response = await client.GetAsync("http://api.usa.gov/jobs/search.json?query=nursing+jobs");
        var model = await response.Content.ReadAsAsync>();
    

提交回复
热议问题