Copied to clipboard

Flag this post as spam?

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


  • Sandra26 4 posts 94 karma points
    6 days ago
    Sandra26
    0

    Serializing Umbraco.Content(id) to JSON

    Hello , I'm New to Umbraco and I want to create Web Api. So I need help how to serialize IPublishedContent in JSON.

  • Louis Jackson-Rees 102 posts 333 karma points c-trib
    6 days ago
    Louis Jackson-Rees
    0

    With Newtonsoft.Json you can:

    JsonConvert.SerializeObject(Umbraco.Content(id))

    But i have done this in the past and it often crashes as the IPublishedContent object is so large, i would advise mapping the IPublishedContent item to a custom model manually or using models builder, and then serialise that model instead.

  • Steven Baker 7 posts 77 karma points
    6 days ago
    Steven Baker
    0

    Hi Sandra,

    Best to use the UmbracoApiController class to manage a transformation of IPublishedContent as the object is too complex for JSON deserialization. You can map it to a less complex object and expose it through the controller. The controller already has access to the Umbraco Helper class which will allow you to do things link query IPC.

    Look at the documentation here:

    https://our.umbraco.com/documentation/Reference/Routing/WebApi/

    Good luck,

    Steve

  • Lee Kelleher 3876 posts 14589 karma points MVP 9x admin c-trib
    6 days ago
    Lee Kelleher
    100

    Hi Sandra26,

    As the others say, out-the-box, serializing IPublishedContent object will throw various errors. The only way to do it is with a custom resolver for JSON.NET.

    See this thread for the code...
    https://our.umbraco.com/forum/umbraco-8/98381-serializing-an-publishedcontentmodel-modelsbuilder-model-in-v8#comment-310148

    Then you should be able to do something like this...

    @{
        var settings = new JsonSerializerSettings
        {
            ContractResolver = new PublishedContentContractResolver()
        };
        var serialized = JsonConvert.SerializeObject(l, Formatting.Indented, settings);
    }
    

    Hope this helps.

    Cheers,
    - Lee

  • Sandra26 4 posts 94 karma points
    2 days ago
    Sandra26
    0

    Thank you very much for your answers, they were really helpful. You all have a nice day , Sandra

Please Sign in or register to post replies

Write your reply to:

Draft