Azure Functions – Convert Json to Xml with newtonsoft
2016, Aug 03
I’m in the midst of putting together a few Azure Functions to use with Logic Apps.
This one is pretty simple, and demonstrates a couple of concepts so I thought I’d share.
{
"bindings": [
{
"name": "req",
"type": "httpTrigger",
"direction": "in",
"webHookType": "genericJson"
},
{
"name": "res",
"type": "http",
"direction": "out"
}
],
"disabled": false
}
#r "Newtonsoft.Json"
using System;
using System.Net;
using System.Xml;
using Newtonsoft.Json;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
log.Info($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}");
string jsondoc = await req.Content.ReadAsStringAsync();
if (jsondoc == null ) {
return req.CreateResponse(HttpStatusCode.BadRequest, new {
error = "Please post JsonDoc"
});
}
else {
try {
//dynamic data = JsonConvert.DeserializeObject(jsondoc);
//log.Info($"{data.ModuleHeader.SignOnDate}");
//create root
XmlDocument xDoc = JsonConvert.DeserializeXmlNode(jsondoc, "newrootnode");
log.Info($"{xDoc.OuterXml}");
return req.CreateResponse(HttpStatusCode.OK, xDoc.OuterXml);
}
catch(Exception ex){
log.Info($"{ex.ToString()}");
return req.CreateResponse(HttpStatusCode.BadRequest, new {
error = $"Error parsing jsondocument {ex.Message}"
});
}
}
}
{
"frameworks": {
"net46": {
"dependencies": {
"Newtonsoft.Json": "9.0.1"
}
}
}
}