contentful / contentful.net

.NET Library for Contentful's Content Delivery and Management API
MIT License
95 stars 53 forks source link

Could not create an instance of type Contentful.Core.Models.IContent #316

Closed himynameistim closed 9 months ago

himynameistim commented 12 months ago

I'm getting the error "Newtonsoft.Json.JsonSerializationException: 'Could not create an instance of type Contentful.Core.Models.IContent. Type is an interface or abstract class and cannot be instantiated" when trying to Deserialize to a model with a Document in it.

The model looks like this (other properties removed as they all work)

public class Navigation { public SystemProperties Sys { get; set; } public string Title { get; set; } public List<object> PrimaryNavigation { get; set; } }

public class ArticleMenu { public Document Article1Description { get; set; } }

Code that does the deserializing looks like this:

var client = new ContentfulClient(httpClient, options); var builder = new QueryBuilder<Navigation>().ContentTypeIs("navigation").Include(2).Limit(1); var entries = await client.GetEntries<Navigation>(builder);

if (entries.Any()) { var entry = entries.FirstOrDefault(); foreach (var contentfulNavItem in entry.PrimaryNavigation) { var contentfulNavItemDeserialized = JsonConvert.DeserializeObject<Entry<object>>(contentfulNavItem.ToString()); if (contentfulNavItemDeserialized.SystemProperties.ContentType.SystemProperties.Id == "articleMenu") { var contentfulNavItemDeserializedAsArticleMenu = JsonConvert.DeserializeObject<Models.Contentful.ArticleMenu>(contentfulNavItem.ToString()); } } }

The initial query to Contentful gets an item with a Content Type of Navigation which contains a list of items in the navigation. These can be different types but just showing one for simplicity. The call to deserialize when one is an article menu that contains a rich text is the issue.

Article1Descriptions data looks like this

image
Roblinde commented 12 months ago

Hi @himynameistim

I think you probably want to change your List to a strongly typed list if you can. That way you don't have to deserialize the entry yourself. However, if you wish to keep the code as is you need to provide the call to JsonConvert.DeserializeObject with a way to understand rich text structures. What you could do is grab the serializer settings from the ContenfulClient and pass it along.

Something like: JsonConvert.DeserializeObject<Entry<object>>(contentfulNavItem.ToString(), client.SerializerSettings)