Monday, July 7, 2014

To convert from JSON to XML and write

Sometimes, while we retrieve data from web API, the output comes in JSON format which we cannot use as a source in our SSIS ETL. So we need to convert it in to XML. Below is the code to convert.

Here the API output is stored in 's2'. Also we need add some the namespace along with adding them in reference.

using System.Xml;
using System.Xml.Linq;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
using System.Runtime.Serialization.Json;

using Newtonsoft.Json;

public void Main()
{

XmlDocument test1 = JsonToXML(s2);
System.IO.File.WriteAllText(@"D:/Test/Test_Data.xml", test1.InnerXml);

Dts.TaskResult = (int)ScriptResults.Success;

}

public XmlDocument JsonToXML(string json)
        {
            XmlDocument doc = new XmlDocument();

            using (var reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(json), XmlDictionaryReaderQuotas.Max))
            {
                XElement xml = XElement.Load(reader);
                doc.LoadXml(xml.ToString());
            }

            return doc;
        }

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.