Customising a JSON data source

If you want to customise your JSON data being returned from an API call you can use a custom class to transform the JSON into your own format using the JsonRecordType. The class must suitable for deserializing the original JSON and also implement the IJsonTransform interface which enforces the Transform method which returns the deserialized JSON data in the new format. In this example the Laureates information in the following API call https://api.nobelprize.org/v1/prize.json is transformed into HTML paragraphs from a list

Loading...
Razor code

var gridModel = new GridModel(DataSourceType.JSON, "https://api.nobelprize.org/v1/prize.json");

gridModel.Columns = new List()
{
    new GridColumn("Year") { Filter = FilterType.Distinct},
    new GridColumn("Category") {  Filter = FilterType.Distinct},
    new GridColumn("Laureates")
};

gridModel.JsonRecordType = new NobelPrizeTransform();
gridModel.Cache = true;

@(await new DbNetSuiteCore.GridControl(HttpContext).Render(gridModel))
Custom NobelPrizeTransform class

     public class NobelPrizeTransform : IJsonTransform
        {
            public List<NobelPrize> prizes { get; set; }
            public object Transform()
            {
                List<TransformedNobelPrizeList> list = prizes.Select(p => new TransformedNobelPrizeList(p.year, p.category, p.laureates) { }).ToList();
                return list;
            }
        }
        public class NobelPrize
        {
            public string year { get; set; }
            public string category { get; set; }
            public List<Laureate> laureates { get; set; }
        }

        public class TransformedNobelPrizeList
        {
            public TransformedNobelPrizeList(string year, string category, List<Laureate> laureates)
            {
                this.year = year;
                this.category = category;
                this.laureates = LaureatesMarkUp(laureates);

            }
            public string year { get; set; }
            public string category { get; set; }
            public string laureates { get; set; }

            private string LaureatesMarkUp(List<Laureate> laureates)
            {
                if (laureates == null)
                {
                    return string.Empty;
                }
                            return $"{string.Join("", laureates.Select(l => $"<p>"<b>{l.surname}, {l.firstname}"</b> - {l.motivation.Replace("\"", "")}"</<p>").ToList())}";
            }
        }

        public class Laureate
        {
            public string id { get; set; }
            public string firstname { get; set; }
            public string surname { get; set; }
            public string motivation { get; set; }
            public string share { get; set; }
        }