JsonContentHandler.cs 2.43 KB
//*************************************************************************************************
// JsonContentHandler.cs
// Owner: Mahipal Kante
//
// Encode/decode JSON format for Web Service response. converts JSON into XML back and forth
//
// Copyright(c) Microsoft Corporation, 2010
//*************************************************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Xml.XPath;

namespace WebTest.WebService.Plugin.Runtime
{
    public class JsonContentHandler : ContentHandler
    {
        public override string MessageString
        {
            get
            {
                string message = string.Empty;
                System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();

                using (var stream = new MemoryStream())
                {
                    using (XmlDictionaryWriter writer = JsonReaderWriterFactory.CreateJsonWriter(stream, encoding))
                    {
                        this.XmlDocument.WriteTo(writer);
                    }
                    message = encoding.GetString(stream.ToArray());
                }

                return message;
            }
            set
            {
                this.jsonMessage = value;
                this.XmlString = string.Empty;
            }
        }

        public override XPathDocument XPathDocument
        {
            get
            {
                return new XPathDocument(GetReader());
            }
        }

        protected override void LoadDocument()
        {
            try
            {
                this.XmlDocument = new XmlDocument();
                this.XmlDocument.Load(GetReader());
            }
            catch (Exception)
            {
                // try setting it as an XML
                this.XmlString = jsonMessage;
            }
        }

        private XmlDictionaryReader GetReader()
        {
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();

            XmlDictionaryReader jsonReader =
                System.Runtime.Serialization.Json.JsonReaderWriterFactory.CreateJsonReader(
                encoding.GetBytes(this.jsonMessage),
                XmlDictionaryReaderQuotas.Max);

            return jsonReader;
        }

        private string jsonMessage = string.Empty;
    }
}