Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • nickornotto 403 posts 907 karma points
    May 27, 2022 @ 13:41
    nickornotto
    0

    Is there a way to serialise IPublishedContent to JSON in Umbraco 9?

    I am unable to serialise a content with nested content property in v9 straight to JSON because of Content property self referencing, eg:

    JsonSerializationException: Self referencing loop detected for property 'ContentType' with type 'Umbraco.Cms.Core.Models.PublishedContent.PublishedContentType'. Path 'SearchResult[0].NestedContentItem[0].Item.ItemNc[0].Price[0].ContentType.PropertyTypes[0]'.

    Is there any way of facilitating the serialisation other than map to custom model?

  • Lee Kelleher 4026 posts 15836 karma points MVP 13x admin c-trib
    May 27, 2022 @ 14:58
    Lee Kelleher
    101

    Hi Nick,

    If you are using the Contentment package, (yup, I'm plugging my own package), then there is an undocumented feature to serialize IPublishedContent objects.

    If you aren't using Contentment, that's cool - if you want to copy/paste the source code, it's here: https://github.com/leekelleher/umbraco-contentment/blob/3.3.1/src/Umbraco.Community.Contentment/Web/Serialization/PublishedContentContractResolver.cs

    Then in your controller code, however you are serializing the object to JSON, you can assign the ContractResolver like so...

    SerializerSettings = new JsonSerializerSettings
    {
        ContractResolver = new Umbraco.Community.Contentment.Web.Serialization.PublishedContentContractResolver(),
    }
    

    For reference, (and credit), I adapted the serializer code from this forum post for v8: https://our.umbraco.com/forum/umbraco-8/98381-serializing-an-publishedcontentmodel-modelsbuilder-model-in-v8#comment-310148

    I hope this helps?

    Cheers,
    - Lee

  • nickornotto 403 posts 907 karma points
    Jun 01, 2022 @ 21:57
    nickornotto
    0

    Fantastic! It's a great help.

    I didn't check what's the performance with a larger number of items but will report here if there is any issue later.

    Thanks!

Please Sign in or register to post replies

Write your reply to:

Draft