Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newtonsoft.Json.Linq.JArray' to type 'System.Collections.Generic.IEnumerable

I am calling my web api from my C# desktop client.

This is my code on the client:

public IEnumerable<Model.Print> Get()
{
    var print = new List<Model.Print>();

    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(Shared.URL);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(Shared.HeaderType));
        var response = client.GetAsync(route + "?" + GeneralTags.CUSTOMER_REF + "=" + new Guid().ToString()).Result;

        if (response.IsSuccessStatusCode)
        {
            string strJson = response.Content.ReadAsStringAsync().Result;
            var jObj2 = (IEnumerable<Model.Print>)JsonConvert.DeserializeObject(strJson);
        }
        else
        {
            evError(new Exception(String.Format("{0}: {1}", (int)response.StatusCode, response.ReasonPhrase)), ErrorTags.PRINT_GET);
        }
    }
    return print;
}

But I get an error on this line:

var jObj2 = (IEnumerable<Model.Print>)JsonConvert.DeserializeObject(strJson);

The error is:

'Newtonsoft.Json.Linq.JArray' to type 'System.Collections.Generic.IEnumerable`1[InformedWorkerServer.Model.Print]'.

The strJson contains a value:

[
  {"PrintId":1,"PrintRef":"00000000-0000-0000-0000-000000000000","Header":"header","TC":"tc","CompanyRef":"00000000-0000-0000-0000-000000000000"},
  {"PrintId":2,"PrintRef":"39a10cee-7cb3-4ed3-aec2-293761eed96d","Header":"header","TC":"tc","CompanyRef":"00000000-0000-0000-0000-000000000000"}]

What am i missing?

like image 869
Andrew Simpson Avatar asked Nov 01 '15 13:11

Andrew Simpson


2 Answers

Use JsonConvert.DeserializeObject<T> instead:

var jObj2 = JsonConvert.DeserializeObject<List<Model.Print>>(strJson);
like image 69
kkyr Avatar answered Oct 16 '22 21:10

kkyr


If you would like to format the nested json structure as represented in the image below. you can make use of the below formatter in Newtonsoft.Json.

enter image description here

Solution : var _addressDetails = JsonConvert.DeserializeObject>(Convert.ToString(data.addressDetails));

like image 40
Sachin Mishra Avatar answered Oct 16 '22 20:10

Sachin Mishra