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 partial class JsonsoftExample
public JsonsoftExample() { }
JsonsoftExample(DateTime start, DateTime? end)
this.End = end ?? Start.AddHours(1);
[JsonProperty(Required = Required.Always)]
public DateTime Start { get; set; }
public DateTime End { get; set; }
public partial class JsonsoftExample
public string SomeOtherUnrelatedProperty { get; set; }
public bool ShouldSerializeEnd()
return End != Start.AddHours(1);
public static void Test()
var start = DateTime.Parse("2017-10-11T12:34:34Z", CultureInfo.InvariantCulture);
Test(start, start.AddHours(2));
Test(start, start.AddHours(1));
var badJson = @"{""End"":""2017-10-11T14:34:34+00:00""}";
Console.WriteLine("\nTesting JSON: ");
Console.WriteLine(badJson);
var example3 = JsonConvert.DeserializeObject<JsonsoftExample>(badJson);
Assert.IsTrue(false, "Exception should have been thrown.");
Console.WriteLine("Caught expected exception: " + ex.Message);
public static void Test(DateTime start, DateTime end)
var example = new JsonsoftExample
SomeOtherUnrelatedProperty = "some other unrelated property",
var json = JsonConvert.SerializeObject(example);
Console.WriteLine("\nTesting JSON: ");
var example2 = JsonConvert.DeserializeObject<JsonsoftExample>(json);
Assert.IsTrue(example.Start == example2.Start, "start");
Assert.IsTrue(example.End == example2.End, "end");
Assert.IsTrue(example.SomeOtherUnrelatedProperty == example2.SomeOtherUnrelatedProperty, "SomeOtherUnrelatedProperty");
Console.WriteLine("{0} deserialized successfully.", example2);
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: ");
public class AssertionFailedException : System.Exception
public AssertionFailedException() : base() { }
public AssertionFailedException(string s) : base(s) { }
public static class Assert
public static void IsTrue(bool value)
public static void IsTrue(bool value, string message)
throw new AssertionFailedException(message ?? "failed");