If you can access the JSON representation of an Entry, then you can convert that JSON to an Entry Model (https://deliverystack.wordpress.com/2020/07/20/net-core-headless-cms-entry-models-and-entry-model-classes/).
This functionality works well as a .NET extension method (https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods).
This example uses the Contentstack .NET SDK (https://www.contentstack.com/docs/platforms/dot-net/api-reference/api/index.html) for the following reasons:
- Contentstack provides a default Entry Model class (https://www.contentstack.com/docs/platforms/dot-net/api-reference/api/Contentstack.Core.Models.Entry.html, https://github.com/contentstack/contentstack-dotnet/blob/master/Contentstack.Core/Models/Entry.cs) that makes it convenient to demonstrate how you might use this functionality.
- I am most familiar with Contentstack.
- Contentstack has Modular Blocks (https://www.contentstack.com/docs/developers/create-content-types/modular-blocks/), which require custom JsonConverters, and so (in the future) make the best demonstration for this type of logic.
The .NET SDKs for all headless CMS products provide similar functionality.
This code uses the SerializerSettings property exposed by ContentstackClient. In this case, there may be nothing relevant in those settings. In other cases, this is a convenient way to avoid initializing a new SerializerSetttings, specifically to add JsonConverters for Modular Blocks and other features, the logic for which I would want to implement only once and in one place. To avoid exposing vendor-specific APIs in your Entry Models, you may want to copy the JObject to a property in your Entry Model after instantiating that Entry Model. Update: https://deliverystack.net/2020/07/23/expose-entry-json-from-entry-model/
This code also demonstrates how you can retrieve a single simple Field Value from the default Entry Model class. Because every Entry in Contentstack has a Title field, the default Entry Model class has a Title property that you can access. For other properties, you can access values from JSON through the Object property of the default Entry Model class or you may prefer to use the JObject exposed by the ToJson() method of that class, which returns the JObject used to deserialize the JSON to an Entry Model in this example. Optimally, you would use an Entry Model populated implicitly by deserialization rather than accessing the JSON directly in any manner.
2 thoughts on “Convert Entry JSON to Entry Model”