0

I want to use DataTable for DeserializeObject but getting error this error after request API:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: The best overloaded method match for 'Newtonsoft.Json.JsonConvert.DeserializeObject(string, Newtonsoft.Json.JsonSerializerSettings)' has some invalid arguments
at CallSite.Target(Closure , CallSite , Type , Object , Type )

public readonly HttpClient _httpClient;

public SubjectController()
{
    _httpClient = new HttpClient();
}

[Route("Subjects")]
[HttpGet]
public async Task<DataTable> Subjects()
{
    DataTable dt = new DataTable();

    _httpClient.DefaultRequestHeaders.Accept.Clear();
    _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    var response = await _httpClient.GetAsync("http://localhost:41260/api/Subject/GetAllSubjects");

    if (response.IsSuccessStatusCode)
    {
        dynamic result = response.Content.ReadAsStringAsync();
        dt = (DataTable)JsonConvert.DeserializeObject(result, typeof(DataTable));
    }

    return dt;
}
haldo
  • 14,512
  • 5
  • 46
  • 52

1 Answers1

0

You're not awaiting the result of ReadAsStringAsync() which is causing the issue. ReadAsStringAsync returns a string, not dynamic, and DeserializeObject only takes a JSON string as it's first parameter. So you can update your code to:

...
    string result = await response.Content.ReadAsStringAsync();
    dt = (DataTable)JsonConvert.DeserializeObject(result, typeof(DataTable));
haldo
  • 14,512
  • 5
  • 46
  • 52
  • DataTables can be large, so better to use `await response.Content.ReadAsStreamAsync()` and deserialize directly from the stream. See: [Efficient api calls with HttpClient and JSON.NET](https://johnthiriet.com/efficient-api-calls/) and [Json.Net deserialize out of memory issue](https://stackoverflow.com/q/33480477/3744182). – dbc Jan 22 '22 at 01:19