JSON to XML conversion in Ventuz 3 with C#

Ashley premium website template

JSON TO XML CONVERSION IN VENTUZ 3 WITH C#

Ventuz 3 does not have native JSON support. Although most Web APIs deliver XML some only deliver JSON data. To integrate data from the latter into a Ventuz 3 scene a library like Json.NET will help you manage this task.

Preparation

Go to http://james.newtonking.com/json and download the latest release of json.NET (Version 5.0.5 was the latest when this article was written).

To work with external libraries inside Ventuz 3 you have to add them to the Global Assembly Cache. The GAC is something like a version control system for .net assemblies (see wikipedia for more information about GAC) There are some prerequisites a library has to fulfill to be accepted in GAC - Json.NET fulfills all of them (at least in the latest version) so we don’t have to worry about this.

Extract the archive and go to the folder that reflects your latest .net runtimes version number. Open a command line with administrator privileges and go to the downloaded folder with the appropriate dll. Add the dll to your GAC with gacutil.exe /i Newsoft.json.dll (If gacutil was not found search for it in your .net frameworks installation directory.)

console_gac .png

the script:

Fire up Ventuz 3, add a C# script node and open up the editor with a double-click on the node. Below the Custom Model editor (on the left) you will find the Reference editor. It contains a list of all assemblies your script depends on. To add the json.NET assembly right-click on GAC Assemblies and choose Newtonsoft.Json in the latest Version - confirm with ok and the assembly gets added to your script.

console_gac .png

In the editor you will see some default code provided by Ventuz. Right at the top add the following Namespaces.

using Newtonsoft.Json;   //provides JSON conversion and processing functionality.
using System.Net;    //provides network features like WebRequests etc.
using System.Xml;    //provides XML functionality
using System.IO;     //provides Streamreader to process response from WebRequest
using System.Threading;  //to prevent our script from blocking the scene we will use a separate thread to request for the data  

In the Custom Model editor add

INPUTS

  • method getData

OUTPUTS

  • string xml

With a double click on getData in the custom model editor a dummy function OngetData() is added to the bottom of the functions already existing in your script.

    public bool OngetData(int arg)
    {                          
      
        return false;
    }

Add a request() method of type void below the OngetData() function manually.

 
 //this function needs to be added manually.
    public void request()       
    {

    }

Inside request() the WebRequest is formed and its response will be converted into XML. For the sake of simplicity theres no exception handling!! As an example data source I used Flightaware.com which provides an extensive API for flight data. This API is a payed service - use your own API services data here!


//this function needs to be added manually.
public void request() 
{ 

    
    // Create the request for data. See your API providers documentation for details. In this case weather data on John F. Kennedy Airport is requested.
    WebRequest request = WebRequest.Create(„http://flightxml.flightaware.com/json/FlightXML2/MetarEx?airport=KJFK&startTime=0&howMany=1&offset=0");

    // Flightaware needs user credentials for their service.
    request.Credentials = new NetworkCredential("USER", „API_KEY");

    // Convert the response into a string format so json.NET can handle it. 
    WebResponse response = request.GetResponse();
    Stream dataStream = response.GetResponseStream();
    StreamReader reader = new StreamReader (dataStream);
    string responseFromServer = reader.ReadToEnd();

    // Convert the string to an XML document json.net provides deserializers/converters from   and to a lot of different formats.
    XmlDocument doc = (XmlDocument)JavaScriptConvert.DeserializeXmlNode(responseFromServer);

    // with .OuterXML all content of doc is transformed into a string.
    xml = doc.OuterXml;

    //changed tells our script that an output value was changed.
    changed = true;      

    // Clean up streams and response.
    reader.Close();
    response.Close();

    

 }

If you would now invoke request() directly your scene would be blocked until WebRequest got its response. This is where threading comes in. Instead of starting request() as a function, we start it as a thread through the function OngetData().

 
//this function was added through Custom Model Editor.
public bool OngetData()    
{ 

    Thread t = new Thread (request);     //Thread initialization 
    t.Start();                          //Thread gets started

    return false;

    

 }

Invoke getData() and as soon as the response is converted the output xml will contain the converted data as a string. Feed this string into an XML Text node to process it further with Ventuz 3’s extensive XML features .

getdata_XML.png

here is the complete script:

using System;
using Ventuz.Kernel;
using Newtonsoft.Json;   //provides JSON conversion and processing functionality.
using System.Net;    //provides network features like WebRequests etc.
using System.Xml;    //provides XML functionality
using System.IO;     //provides Streamreader to process response from WebRequest
using System.Threading;  //to prevent our script from blocking the scene we will use a separate thread to request for the data  
public class Script : ScriptBase, System.IDisposable
{
    // This member is used by the Validate() method to indicate
    // whether the Generate() method should return true or false
    // during its next execution.
    private bool changed;
    
    // This Method is called if the component is loaded/created.
    public Script()
    {
        // Note: Accessing input or output properties from this method
        // will have no effect as they have not been allocated yet.
    }
    
    // This Method is called if the component is unloaded/disposed
    public virtual void Dispose()
    {
    }
    
    // This Method is called if an input property has changed its value
    public override void Validate()
    {
        // Remember: set changed to true if any of the output 
        // properties has been changed, see Generate()
    }
    
    // This Method is called every time before a frame is rendered.
    // Return value: if true, Ventuz will notify all nodes bound to this
    //               script node that one of the script's outputs has a
    //               new value and they therefore need to validate. For
    //               performance reasons, only return true if output
    //               values really have been changed.
    public override bool Generate()
    {
        if (changed)
        {
            changed = false;
            return true;
        }

        return false;
    }    



    //this function was added automatically by double clicking the getData method created in Custom Model editor
    public bool OngetData(int arg)
    {                          
        Thread t = new Thread (request);     //Thread initialization 
        t.Start();              //Thread gets started

        return false;
    }

    //this function needs to be added manually.
    public void request()       
    {
        // Create the request for data. See your API providers documentation for details. In this case weather data on John F. Kennedy Airport is requested.
        WebRequest request = WebRequest.Create(„http://flightxml.flightaware.com/json/FlightXML2/MetarEx?airport=KJFK&startTime=0&howMany=1&offset=0");
    
        // Flightaware needs user credentials for their service.
        request.Credentials = new NetworkCredential("USER", „API_KEY");
    
        // Get the response it into the format string so json.NET can handle it. 
        WebResponse response = request.GetResponse();
        Stream dataStream = response.GetResponseStream();
        StreamReader reader = new StreamReader (dataStream);
        string responseFromServer = reader.ReadToEnd();

        // Convert the string to an XML document json.net provides deserializers/converters from   and to a lot of different formats.
        XmlDocument doc = (XmlDocument)JavaScriptConvert.DeserializeXmlNode(responseFromServer);
    
        // with .OuterXML all content of doc is transformed into a string.
        xml = doc.OuterXml;

        //changed tells our script that an output value was changed.
        changed = true;      

        // Clean up streams and response.
        reader.Close();
        response.Close();

    }
}

Client

MediaScreen GmbH

Technology

Ventuz3, C#, XML, Json