简体   繁体   中英

ReadAsAsync calling a WebAPI not reconstituting json to class

I am making a call to a WebAPI that returns some Content from a db via JSON. The content is visible in the JSON (viewed using Fiddler) but when I try to put the response data back into a class all the values are null in the class.

This used to work but now fails. I suspect that I may not be using the GetAsync and ReadAsAsync correctly.

new note This is one example but there are several other similar calls that cause the same issue.

Any thoughts why this has stopped working? and what would be the correct way to fix it?

The Class:

 public class ContentElement : ICloneable
{
    public object Clone()
    {
        return this.MemberwiseClone();
    }
    public int PageId { get; set; }
    public string LanguageCode { get; set; }
    public int ContentId { get; set; }
    public string PageName { get; set; }
    public string Content { get; set; }
    public int? DisplayOrder { get; set; }
}

The Code:

 public static List<ContentElement> GetContent(int siteId)
    {
        var contentElements = new List<ContentElement>();
        using (HttpClient client = new HttpClient())
        {
            client.BaseAddress = new Uri(GlobalValues.APIUri);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            AddAuthenticationHeader(client);
            var result = client.GetAsync("api/Content/GetContent/" + (object)siteId).Result;
            if (result.IsSuccessStatusCode)
            {
                contentElements.AddRange((IEnumerable<ContentElement>)result.Content.ReadAsAsync<List<ContentElement>>().Result);
            }
        }
        return contentElements;
    }

The JSON:

[{"PageId":1,"LanguageCode":"en","ContentId":5,"PageName":"Greeting",
"Content":"Content goes here","DisplayOrder":1,"Image":null,"ContentType":"Text"}]

Your json has "Image" and"ContentType" properties, but your class does not. Add these as properties to your class. .NET cannot deserialize the json in your class because it does not have the EXACT same properties as the class.

 public class ContentElement : ICloneable
{
    public object Clone()
    {
        return this.MemberwiseClone();
    }
    public int PageId { get; set; }
    public string LanguageCode { get; set; }
    public int ContentId { get; set; }
    public string PageName { get; set; }
    public string Content { get; set; }
    public int? DisplayOrder { get; set; }
    public byte[] Image { get; set; } //not sure what type this should be
    public string ContentType { get; set; }
}

EDIT A workaround fix for this is to use Newtonsoft.Json to deserialize the json instead of using the .NET function.

contentElements.AddRange((IEnumerable<ContentElement>)JsonConvert.Deserialize<IEnumerable<ContentElement>>(result.Content));
 public async static Task<List<ContentElement>> GetContent(int siteId)
        {
            var contentElements = new List<ContentElement>();
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(GlobalValues.APIUri);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                AddAuthenticationHeader(client);
                var result =await client.GetAsync("api/Content/GetContent/" + (object)siteId);
                if (result.IsSuccessStatusCode)
                {
                    contentElements.AddRange((IEnumerable<ContentElement>)result.Content.ReadAsStringAsync<List<ContentElement>>());
                }
            }
            return contentElements;
        }

make the method async and use await like this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM