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

2

7

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?

Fauna answered 1/11, 2015 at 13:29 Comment(0)
B
14

Use JsonConvert.DeserializeObject<T> instead:

var jObj2 = JsonConvert.DeserializeObject<List<Model.Print>>(strJson);
Borehole answered 1/11, 2015 at 13:38 Comment(1)
Hi, thanks for your answer. This does work on Desktop but not on Raspberry PI2 - which i did not stipulate. But it worked for this forum. ThanksFauna
T
3

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));

Talich answered 5/12, 2017 at 13:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.