Archive for June, 2011

[C#] JSON to XML (snippet)

OK so I have noticed that more and more people are using JSON for there API’s.
Now this I know can be seen as tricky for some to use, so what I have done today is gather some code together to convert JSON to a more familuar Markup language XML.

1st things 1st
Without the dll from James Newton King, I would not have been able to do this.
Also you will need to download said dll for use with this example code. || DOWNLOAD LINK.

Now to the code, here it is.
Its just an example of how you can do it, and is provided as is!

using System;
using System.IO;
using System.Net;
using System.Windows.Forms;
using System.Xml;
using Newtonsoft.Json;

namespace JSON2XML
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e1)
        {
            /* because the origional JSON string has multiple root's this needs to be added */
            string json = "{BFBC2_GlobalStats:";
            json += DownlodUrl("http://api.bfbcs.com/api/xbox360?globalstats");
            json += "}";

            XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
            textBox1.Text = GetXmlString(doc);
        }

        private string DownlodUrl(string url)
        {
            string result = null;
            try
            {
                WebClient client = new WebClient();
                result = client.DownloadString(url);
            }
            catch (Exception ex)
            {
                // handle error
                result = ex.Message;
            }
            return result;
        }

        private string GetXmlString(XmlDocument xmlDoc)
        {
            StringWriter sw = new StringWriter();
            XmlTextWriter xw = new XmlTextWriter(sw);
            xw.Formatting = System.Xml.Formatting.Indented;
            xmlDoc.WriteTo(xw);
            return sw.ToString();
        }
    }
}

Forrst

Well today I finally got into Forrst

A massive thanks goes out to Zack Kitzmiller @ZackKitzmiller who I now know is STAFF on Forrst.

Well if you want come check me out http://forrst.me/djekl