In the last article, we explained how to create an ASP.NET Web API to merge templates with JSON data in the payload body of an HTTP request. The focus of this article was on the Web API and RESTful services itself.

Extracted from this project, this sample shows how to merge a template with a JSON string directly. The JSON data string has the following form:

"street":"9774 Kings Drive",
"phone":"123 898 2298",
"name":"Thin-Jam Hex Nut 4",
"name":"ML Road Frame - Red, 58",
view raw data.json hosted with ❤ by GitHub

It is the JSON representation of a flat XML file with nested data tables created with Newtonsoft.Json:

// load the data as XML
XmlDocument doc = new XmlDocument();
// the Web API expects the data as a JSON object
// 'JsonConvert' converts the XML to the required JSON format
string jsonText = JsonConvert.SerializeXmlNode(doc);
view raw createJSON.cs hosted with ❤ by GitHub

The following method accepts a template name and the JSON string as parameters. The JSON string is converted back to an XML file which is then converted to a DataSet object.

private void MergeTemplate(string templateName, string JsonData)
// creating a new ServerTextControl and MailMerge class
using (ServerTextControl tx = new ServerTextControl())
MailMerge mailMerge = new MailMerge();
mailMerge.TextComponent = tx;
// load the template
mailMerge.LoadTemplate(Server.MapPath("templates/" + templateName),
// create a new DataSet object
DataSet ds = new DataSet();
XmlDocument doc;
// convert the JSON string to an XML document
// object using Newtonsoft.Json
doc = JsonConvert.DeserializeXmlNode(JsonData);
lblError.Visible = false;
catch (Exception exc)
lblError.Visible = true;
lblError.Text = exc.Message;
DocumentViewer1.Visible = false;
// convert the XML to a DataSet
XmlNodeReader reader = new XmlNodeReader(doc);
ds.ReadXml(reader, XmlReadMode.Auto);
// merge the template with the DataSet
// load the resulting document into the DocumentViewer
byte[] data;
mailMerge.SaveDocumentToMemory(out data, BinaryStreamType.InternalUnicodeFormat, null);
DocumentViewer1.LoadDocumentFromMemory(data, FileFormat.InternalUnicodeFormat);
view raw index.aspx.cs hosted with ❤ by GitHub

Finally, the document is merged by calling the Merge method. The resulting document is loaded into the ASP.NET DocumentViewer for visualization.

Using MailMerge with JSON data

Download the sample from GitHub and test it on your own.