Amending DXA JSON

January 18th, 2018 | Posted by Robert Curlette in DXA

Sometimes you may wish to add additional content into the default DXA JSON content that is published to the Broker that are not part of the default Component Fields. In my situation I would like to have fields from the Page and Structure Group Metadata available in my DXA view. While using DXA 1.7 there is no out of the box, or ‘accelerated’, way to do this. My idea is to create an additional C# TBB, and in that access the DXA JSON and also add a field to it. The advantage to this approach is that the additional field will be seen by the DXA runtime as a Page Metadata field, and therefore serialized and available to us in the View without doing anything special on the DXA Frontend Webapp.

In this post I will share a sample app I used to access the DXA JSON and add an additional property into the MetadataFields collection. It was quite tricky to get this code to work, as we need to use the ‘dynamic’ type in C#, and this is without intellisense, so finding the appropriate methods and properties to use was a bit of a challenge. You will need to add the Newtonsoft JSON library from Nuget to get the code to work.

In a future article I will share more about the C# TBB that uses this code. The dxa.json file is the output of the Generate Dynamic Page (DXA) TBB form Template Builder. Also, in the code below, I only show an example for a text field, and I also do not product the JSON for XPM – as I have no intention of using XPM on these ‘fake’ Page Metadata fields.

using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using System;

namespace temp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = System.IO.File.ReadAllText(@"C:\RC\dxa.json");
            dynamic jsonObject = JObject.Parse(text);
            dynamic meta = jsonObject.MetadataFields;

            dynamic zone = new JObject();
            zone.Name = "zone";

            List values = new List()
            {
               "value"
            };

            dynamic array = JArray.FromObject(values);
            zone.Values = array;
            zone.FieldType = 0;  // text type, need to change if other field type

            // title is a mandatory metadata field on the Page
            meta.Property("title").AddAfterSelf(new JProperty("zone", zone));

            Console.ReadLine();
        }
    }
}

You can follow any responses to this entry through the RSS 2.0 You can leave a response, or trackback.

Leave a Reply

Your email address will not be published. Required fields are marked *