using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
public static ObjectId Create()
return new ObjectId(Interlocked.Increment(ref lastId));
public int Id { get { return id + 1; } private set { id = value - 1; } }
public ObjectId Next { get { return new ObjectId(Id + 1); } }
public class MaxDepthJsonTextWriter : JsonTextWriter
public int? MaxDepth { get; set; }
public int MaxObservedDepth { get; private set; }
public MaxDepthJsonTextWriter(TextWriter writer, JsonSerializerSettings settings)
this.MaxDepth = (settings == null ? null : settings.MaxDepth);
this.MaxObservedDepth = 0;
public MaxDepthJsonTextWriter(TextWriter writer, int? maxDepth)
this.MaxDepth = maxDepth;
public override void WriteStartArray()
public override void WriteStartConstructor(string name)
base.WriteStartConstructor(name);
public override void WriteStartObject()
private void CheckDepth()
MaxObservedDepth = Math.Max(MaxObservedDepth, Top);
throw new JsonSerializationException(string.Format("Depth {0} Exceeds MaxDepth {1} at path \"{2}\"", Top, MaxDepth, Path));
public string Value { get; set; }
public ObjectId ObjectId;
public static void Test()
var myClass = new TestClass { ObjectId = ObjectId.Create() };
var myList = Enumerable.Range(0, 10).Select(i => new TestClass { ObjectId = ObjectId.Create() }).ToList();
Assert.DoesNotThrow(() => Test(new [] { 1, 2, 3 }, 1));
Assert.DoesNotThrow(() => Test(ObjectId.Create(), 1));
Assert.DoesNotThrow(() => Test(new SimpleClass { Value = "some value" }, 1));
Assert.DoesNotThrow(() => Test(new SimpleClass { Value = "some value" }, 2));
Assert.DoesNotThrow(() => Test(new SimpleClass { Value = "some value" }, 3));
Assert.DoesNotThrow(() => Test(myClass, 3));
Assert.DoesNotThrow(() => Test(myClass, 2));
Assert.Throws<JsonSerializationException>(() => Test(myClass, 1));
Assert.DoesNotThrow(() => Test(myList, 3));
Assert.Throws<JsonSerializationException>(() => Test(myList, 2));
static void Test<T>(T root, int maxDepth)
var settings = new JsonSerializerSettings { MaxDepth = maxDepth };
Console.WriteLine("Testing serialization of {0} with MaxDepth {1}:", root, maxDepth);
using (var writer = new StringWriter())
using (var jsonWriter = new MaxDepthJsonTextWriter(writer, settings))
JsonSerializer.Create(settings).Serialize(jsonWriter, root);
json = writer.ToString();
Console.Write(" passed, result: ");
Console.WriteLine(" failed with exception {0}", ex.Message);
public static void Main()
Console.WriteLine("Environment version: " + Environment.Version);
Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine("Failed with unhandled exception: ");