Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
himynameistim opened this issue Sep 18, 2023 · 1 comment
Closed

Comments

@himynameistim
Copy link

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
Copy link
Collaborator

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants