Manipulating JSON using Json.NET

Json.NET makes it convenient to manipulate JSON in C# using dynamic programming. Let’s start with a JSON representation we want to create

	"menu": {
		"id": "file",
		"value": "File",
		"popup": {
			"menuitem": [
					"value": "New",
					"onclick": "CreateNewDoc()"
					"value": "Open",
					"onclick": "OpenDoc()"
					"value": "Close",
					"onclick": "CloseDoc()"

Here’s how the Json.NET object representation can be created in C# using dynamic programming

dynamic jobj = JObject.FromObject(new 
	menu = new
		id = "file",
		value = "File",
		popup = new
			menuitem = new []
					value = "New",
					onclick = "CreateNewDoc()"
					value = "Open",
					onclick = "OpenDoc()"
					value = "Close",
					onclick = "CloseDoc()"

To serialize it

var json = JsonConvert.SerializeObject(jobj);

To deserialize JSON string representation to dynamic object

dynamic jobj = JsonConvert.DeserializeObject(json);

It is fairly easy to extend the object representation and add new items = new JArray()
	new JObject() {
		new JProperty("bar", 10)
	new JObject() {
		new JProperty("bar", 20)

That adds a new property to jobj called foo, that references an array containing two objects. It demonstrates creation of object representations entirely using Json.NET.

Create XML documents in LINQ

I’ve created XML documents using string concatenation, and DOM implementations, in the past. LINQ in .NET provides an interesting mechanism for document creation.

I’ll use the following XML document obtained from IETF’s PIDF-LO spec, as an example

<presence xmlns="urn:ietf:params:xml:ns:pidf" xmlns:dm="urn:ietf:params:xml:ns:pidf:data-model" xmlns:gp="urn:ietf:params:xml:ns:pidf:geopriv10" xmlns:gml="" xmlns:cl="urn:ietf:params:xml:ns:pidf:geopriv10:civicAddr" entity="">
	<dm:device id="mikepc">
				<gml:Point srsName="urn:ogc:def:crs:EPSG::4326">
					<gml:pos>-43.5723 153.21760</gml:pos>

Note that the document uses multiple schemas. This is how LINQ’s functional document creation can be used to recreate the above document using C#

XNamespace pidf = "urn:ietf:params:xml:ns:pidf";
XNamespace dm = "urn:ietf:params:xml:ns:pidf:data-model";
XNamespace gp = "urn:ietf:params:xml:ns:pidf:geopriv10";
XNamespace gml = "";
XNamespace cl = "urn:ietf:params:xml:ns:pidf:geopriv10:civicAddr";
XElement presence = new XElement(
	pidf + "presence",
	new XAttribute("xmlns", pidf.NamespaceName),
	new XAttribute(XNamespace.Xmlns + "dm", dm.NamespaceName),
	new XAttribute(XNamespace.Xmlns + "gp", gp.NamespaceName),
	new XAttribute(XNamespace.Xmlns + "gml", gml.NamespaceName),
	new XAttribute(XNamespace.Xmlns + "cl", cl.NamespaceName),
	new XAttribute("entity", ""),
	new XElement(
		dm + "device",
		new XAttribute("id", "mikepc"),
		new XElement(
			gp + "geopriv",
			new XElement(
				gp + "location-info",
				new XElement(
					gml + "Point",
					new XAttribute("srsName", "urn:ogc:def:crs:EPSG::4326"),
					new XElement(gml + "pos", "-43.5723 153.21760")
				new XElement(
					cl + "civicAddress",
					new XElement(cl + "FLR", 2)
			new XElement(gp + "usage-rules", ""),
			new XElement(gp + "method", "Wiremap")
		new XElement(dm + "deviceID", "mac:8asd7d7d70cf"),
		new XElement(dm + "timestamp",  DateTime.UtcNow.ToString("yyyy-MM-ddThh:mm:ssZ"))

XDocument presenceDocument = new XDocument(presence);

WebSockets with WCF

This post demonstrates an elementary chat service constructed using WCF and WebSockets. A custom binding that leverages WebSocket support in httpTransport is used. JSON is serialized and deserialized using byteStreamMessageEncoding encoding. Use httpsTransport for secure transport.

Service interface

The service interface is used to receive connection requests and messages from clients. It has only one method, as shown below.

using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Threading.Tasks;

namespace ChatService
    [ServiceContract(CallbackContract = typeof(IChatServiceCallback))]
    interface IChatService
        [OperationContract(IsOneWay = true, Action = "*")]
        Task SendMessage(Message message);

Callback interface

The callback interface is used to send messages back to the clients.

using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Threading.Tasks;

namespace ChatService
    interface IChatServiceCallback
        [OperationContract(IsOneWay = true, Action = "*")]
        Task ReceiveMessage(Message message);

Service implementation

The service implementation receives messages from clients, and fires them off to other clients, using their respective callback interface. Messages are sent to clients who have sent messages to a chat room, and are still connected.

using System;
using System.Collections.Concurrent;
using System.IO;
using System.Net.WebSockets;
using System.Runtime.Serialization.Json;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Threading.Tasks;

namespace ChatService
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class ChatServiceImplementation : IChatService
        static ConcurrentDictionary<string, ConcurrentDictionary<string, Chatter>> rooms = 
            new ConcurrentDictionary<string, ConcurrentDictionary<string, Chatter>>();

        public async Task SendMessage(Message message)
            if (message.IsEmpty) return;

            byte[] body = message.GetBody<byte[]>();
            MemoryStream stream = new MemoryStream(body);
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Chatter));
            Chatter chatter = (Chatter)ser.ReadObject(stream);
            IChatServiceCallback callback = OperationContext.Current.GetCallbackChannel<IChatServiceCallback>();
            chatter.Callback = callback;

            IChannel channel = (IChannel)callback;
            channel.Faulted += channel_Faulted;
            channel.Closed += channel_Closed;

            ConcurrentDictionary<string, Chatter> room;
            if (!rooms.TryGetValue(chatter.Room, out room))
                room = new ConcurrentDictionary<string, Chatter>();
                rooms.TryAdd(chatter.Room, room);
            Chatter existingChatter;
            if (!room.TryGetValue(chatter.Nickname, out existingChatter))
                room.TryAdd(chatter.Nickname, chatter);
            else if (existingChatter.Callback != chatter.Callback)
                existingChatter.Callback = chatter.Callback;
            foreach (Chatter c in room.Values)
                if (((IChannel)c.Callback).State == CommunicationState.Opened)
                    await c.Callback.ReceiveMessage(CreateMessage(body));

        private void channel_Closed(object sender, EventArgs e)
            // Clean up

        private void channel_Faulted(object sender, EventArgs e)
            // Clean up

        private Message CreateMessage(byte[] message)
            Message channelMessage = ByteStreamMessage.CreateMessage(new ArraySegment<byte>(message));

            channelMessage.Properties["WebSocketMessageProperty"] =
                new WebSocketMessageProperty { MessageType = WebSocketMessageType.Text };

            return channelMessage;

Here’s the Chatter class, used to store state.

using System.Runtime.Serialization;

namespace ChatService
    class Chatter : IExtensibleDataObject
        [DataMember(Name = "nickname", IsRequired = true)]
        public string Nickname { get; set; }
        [DataMember(Name = "room", IsRequired = true)]
        public string Room { get; set; }
        [DataMember(Name = "message", IsRequired = true)]
        public string Message { get; set; }
        public IChatServiceCallback Callback { get; set; }

        public ExtensionDataObject ExtensionData { get; set; }


App.config below creates a customBinding and associates it with the chat service.

<?xml version="1.0" encoding="utf-8"?>
        <binding name="webSocketHttpBinding">
            <webSocketSettings transportUsage="Always" createNotificationOnConnection="true"/>
      <service name="ChatService.ChatServiceImplementation">
        <endpoint address="http://localhost:8004/chatservice" binding="customBinding" bindingConfiguration="webSocketHttpBinding" contract="ChatService.IChatService"/>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>

Self hosted console app

A console app that hosts the service is shown below.

using System;
using System.ServiceModel;

namespace ChatServiceHost
    class Program
        static void Main(string[] args)
            ServiceHost host = new ServiceHost(typeof(ChatService.ChatServiceImplementation));

            Console.WriteLine("Hit Enter to quit.");

Chat web page

The following web page uses jQuery and WebSocket to send/receive messages to/from chat rooms.

<!DOCTYPE html>

<html lang="en" xmlns="">
    <meta charset="utf-8" />
    <script type="text/javascript"
        Nickname <br/>
        <input id="nickname" type="text" value="nickname" /><br/>
        Room <br />
        <input id="room" type="text" value="room" /><br/>
        Message <br />
        <input id="message" type="text" value="message" /><br/>
        <input id="send" type="button" value="Send" />

        <div id="messages">

    <img src="image/HTML5_Logo_64.png" />

    <script type="text/javascript">
        var url = 'ws://localhost:8004/chatservice'; // base url
        var connection = null;
        function documentReady() {
        function sendClick() {
            if (connection == null) {
                connection = new WebSocket(url);
            } else {
            connection.onopen = sendMessage;
            connection.onmessage = receiveMessage;
            connection.onerror = function (e) {
                alert('error ' + e);
                connection = null;
        function sendMessage() {
            var chatter = new Object();
            chatter.nickname = $('#nickname').val();
   = $('#room').val();
            chatter.message = $('#message').val();
        function receiveMessage(e) {
            var chatter = JSON.parse(;
            var message = chatter.nickname + '@' + + ' said ' + chatter.message + '<br/>';


Open the HTML file in a modern web browser, and you’ll see the chat page. Open the same page in additional tabs. Once you send a message to one or more chat rooms in a tab, messages posted from other tabs using different nicknames to the same chat rooms, should appear in the Messages area in reverse chronological order.

One really pesky problem is the following exception you get, when you try to send the same Message instance to multiple callbacks
A property with the name 'TransactionFlowProperty' already exists..

I have also experimented with testing scalability by hitting the service using thor, and have noted that InstanceContextMode.Single behavior is the most responsive and reliable.

The source code is available from GitHub. I’d like to acknowledge Zhuyun Dai’s article at CodeProject for giving useful insights with regards to using byteStreamMessageEncoding.

A note on Hungarian notation

Back in the old days of Visual Basic, I got into the habit of using the Hungarian notation. That habit stuck with me through the Java days, but I’ve kicked it off almost completely now. My conclusion is that variable names should be clear, free of obscure prefixes, and explain their purpose. If I want to know the scope or type of the variable, I’ll just look it up using an IDE or grep.

Please read the post I’ve linked to above, to understand that there are at least two kinds of Hungarian notation. One comes from Charles Simonyi, the other popularized by Charles Petzold.