Copied to clipboard

Flag this post as spam?

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


  • Jonathan Hartley 8 posts 78 karma points
    Dec 13, 2019 @ 19:31
    Jonathan Hartley
    0

    How do I convert rich text editor doctype properties to JSON in Umbraco 8?

    I have a doctype with several properties that are rich text editors. I can grab a list of content items with this doctype with a standard query like the following:

    var items = Umbraco.Content(Guid.Parse("some-guid-322342-23"))
        .ChildrenOfType("doctype-alias-here")
        .Where(x => x.IsVisible())
    

    Then, I convert the items variable to JSON with the following:

    var jsonSerializerSettings = new JsonSerializerSettings();
    jsonSerializerSettings.ContractResolver = new PublishedContentContractResolver();
    var jsonStr = JsonConvert.SerializeObject(items, Formatting.Indented, jsonSerializerSettings);
    

    However, when I do that and echo the JSON string in the template, all the rich text editor properties come back as just {}. In other words, all the content is stripped from the JSON.

    How can I get the rich text editor content to be in the JSON as well? Thank you.

  • Matt Barlow | jacker.io 164 posts 740 karma points c-trib
    Dec 15, 2019 @ 18:31
    Matt Barlow | jacker.io
    3

    It's not clear from your example, what your PublishedContractResolver is.

    Assuming it's the one from the Contentment package by Lee Kelleher?

    https://github.com/leekelleher/umbraco-contentment/blob/839e4828f65c7e2e8fe317d6c898648305f2ab1c/src/Umbraco.Community.Contentment/Web/Serialization/PublishedContentContractResolver.cs

    I tested it as well, and the rte data wasn't being rendered. Found this post on stack overflow:

    https://stackoverflow.com/questions/11350392/how-do-i-serialize-ihtmlstring-to-json-with-json-net/11350394

    public class IHtmlStringConverter : Newtonsoft.Json.JsonConverter
        {
            public override bool CanConvert(Type objectType)
            {
                return typeof(IHtmlString).IsAssignableFrom(objectType);
            }
    
            public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
            {
                IHtmlString source = value as IHtmlString;
                if (source == null)
                {
                    return;
                }
    
                writer.WriteValue(source.ToString());
            }
    
            public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
            {
                // warning, not thoroughly tested
                var html = reader.Value as string;
                return html == null ? null : System.Web.Mvc.MvcHtmlString.Create(html);
            }
        }
    

    So took the converter example and plugged it into Lee's example:

    public sealed class PublishedContentContractResolver : CamelCasePropertyNamesContractResolver
        {
            public static readonly PublishedContentContractResolver Instance = new PublishedContentContractResolver();
    
            private readonly Dictionary<string, JsonConverter> _converterLookup;
            private readonly HashSet<string> _ignoreFromContent;
            private readonly HashSet<string> _ignoreFromProperty;
    
            public PublishedContentContractResolver()
            {
                _converterLookup = new Dictionary<string, JsonConverter>(StringComparer.OrdinalIgnoreCase)
                {
                    { "ItemType", new StringEnumConverter()},
                    { typeof(IHtmlString).FullName, new IHtmlStringConverter()},
    
                };
    
                _ignoreFromContent = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
                {
                    "Children",
                    "ChildrenForAllCultures",
                    "CompositionAliases",
                    "ContentSet",
                    "ContentType",
                    "CreatorId",
                    "Cultures",
                    "Parent",
                    "TemplateId",
                    "WriterId",
                };
    
                _ignoreFromProperty = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
                {
                    "PropertyType",
                    "ReferenceCacheLevel",
                };
            }
    
            protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
            {
                var property = base.CreateProperty(member, memberSerialization);
    
                if (typeof(IPublishedContent).IsAssignableFrom(member.DeclaringType))
                {
                    property.ShouldSerialize = _ =>
                    {
                        return _ignoreFromContent.Contains(property.PropertyName) == false;
                    };
                }
                else if (typeof(IPublishedProperty).IsAssignableFrom(member.DeclaringType))
                {
                    property.ShouldSerialize = _ =>
                    {
                        return _ignoreFromProperty.Contains(property.PropertyName) == false;
                    };
                }
    
                if (_converterLookup.ContainsKey(property.PropertyName))
                {
                    property.Converter = _converterLookup[property.PropertyName];
    
                }else if (_converterLookup.ContainsKey(property.PropertyType.FullName)) {
    
                    property.Converter = _converterLookup[property.PropertyType.FullName];
                }
    
                return property;
            }
        }
    

    Then the rte's are being rendered out! hope that helps.

  • Youngsan 7 posts 77 karma points
    May 19, 2022 @ 01:32
    Youngsan
    0

    Thank you. it works for me

  • Jonathan Hartley 8 posts 78 karma points
    Dec 15, 2019 @ 19:42
    Jonathan Hartley
    0

    That's very helpful. Thanks a ton!

  • vcd 3 posts 72 karma points
    Feb 15, 2020 @ 23:21
    vcd
    0

    Hi, I tried the item serialization first on Umbraco 7, and it worked perfectly, with the additional handling of the rich text editor, as described here, but on Umbraco 8.2.2 - no properties are being serialized, I only get the key, Name, Id, level, path etc. properties. Did anyone else encounter this? Thanks

  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies