Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Render JSON data using MessageTemplates
using System;
using System.Linq;
using MessageTemplates.Core;
using MessageTemplates.Parsing;
using MessageTemplates.Structure;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace MessageTemplateRenderer
/// <summary>
/// Dependencies:
/// "MessageTemplates": "1.0.0-rc-00260",
/// "Newtonsoft.Json": "9.0.1"
/// </summary>
public class Program
public static void Main(string[] args)
var template = "Hello, {Name}, see: {Data}";
var json = @"{""Name"": ""nblumhardt"", ""Data"": {""Counts"": [1, 2, 3]}}";
var properties = (JObject) JsonConvert.DeserializeObject(json);
var parser = new MessageTemplateParser();
var parsed = parser.Parse(template);
var templateProperties = new TemplatePropertyValueDictionary(new TemplatePropertyList(
properties.Properties().Select(p => CreateProperty(p.Name, p.Value)).ToArray()));
var rendered = parsed.Render(templateProperties);
static TemplateProperty CreateProperty(string name, JToken value)
return new TemplateProperty(name, CreatePropertyValue(value));
static TemplatePropertyValue CreatePropertyValue(JToken value)
if (value.Type == JTokenType.Null)
return new ScalarValue(null);
var obj = value as JObject;
if (obj != null)
JToken tt;
obj.TryGetValue("$typeTag", out tt);
return new StructureValue(
obj.Properties().Where(kvp => kvp.Name != "$typeTag").Select(kvp => CreateProperty(kvp.Name, kvp.Value)),
var arr = value as JArray;
if (arr != null)
return new SequenceValue(arr.Select(CreatePropertyValue));
return new ScalarValue(value.Value<object>());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment