Created
October 3, 2016 21:25
-
-
Save nblumhardt/769e34782b300dbbf8b9d4a407802eeb to your computer and use it in GitHub Desktop.
Render JSON data using MessageTemplates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
Console.WriteLine(rendered); | |
} | |
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)), | |
tt?.Value<string>()); | |
} | |
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