Skip to content

Instantly share code, notes, and snippets.

@kendfrey
Created July 24, 2013 18:03
Show Gist options
  • Save kendfrey/6072951 to your computer and use it in GitHub Desktop.
Save kendfrey/6072951 to your computer and use it in GitHub Desktop.
JSON asserting
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Test
{
static class Json
{
public static void CompareJson(string expected, string actual)
{
var serializer = new JavaScriptSerializer();
object expectedValue = serializer.DeserializeObject(expected);
object actualValue = serializer.DeserializeObject(actual);
CompareValue(expectedValue, actualValue);
}
static void CompareValue(object expected, object actual)
{
if (expected is Dictionary<string, object> && actual is Dictionary<string, object>)
{
CompareObject(expected as Dictionary<string, object>, actual as Dictionary<string, object>);
}
else if (expected is object[] && actual is object[])
{
CompareArray(expected as object[], actual as object[]);
}
else
{
Assert.AreEqual(expected, actual);
}
}
static void CompareObject(Dictionary<string, object> expected, Dictionary<string, object> actual)
{
foreach (string key in expected.Keys.Union(actual.Keys))
{
if (!actual.ContainsKey(key))
{
Assert.Fail("Missing property '{0}' in JSON.", key);
}
if (!expected.ContainsKey(key))
{
Assert.Fail("Unexpected property '{0}' in JSON.", key);
}
CompareValue(expected[key], actual[key]);
}
}
static void CompareArray(object[] expected, object[] actual)
{
Assert.AreEqual(expected.Length, actual.Length);
for (int i = 0; i < expected.Length; i++)
{
CompareValue(expected[i], actual[i]);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment