CSharp · Console
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters;
using System.IO;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Xml;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
// https://stackoverflow.com/questions/47119821/net-system-datetime-tolocaltime-returns-invalid-local-time-value
public class RootObject
{
public DateTime foo { get; set; }
}
class TestClass
{
public static void Test()
{
var json = GetJson();
Console.WriteLine("Input JSON: ");
Console.WriteLine(json);
foreach (DateTimeZoneHandling handling in Enum.GetValues(typeof(DateTimeZoneHandling)))
{
Console.WriteLine("\nTesting DateTimeZoneHandling.{0}:", handling);
var settings = new JsonSerializerSettings
{
DateTimeZoneHandling = handling,
};
var root = JsonConvert.DeserializeObject<RootObject>(json, settings);
Console.WriteLine("foo.Kind = {0}, Round-trip XML value = {1}, UTC XML value = {2}",
root.foo.Kind,
XmlConvert.ToString(root.foo, XmlDateTimeSerializationMode.RoundtripKind),
XmlConvert.ToString(root.foo, XmlDateTimeSerializationMode.Utc));
var newJson = JsonConvert.SerializeObject(root);
Console.WriteLine(newJson);
}
Console.WriteLine("\nDone testing.");
}
static string GetJson()
{
var json = @"{
""foo"": ""2017-11-05T08:30:00""
}";
return json;
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Environment version: " + Environment.Version);
Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine();
try
{
TestClass.Test();
}
catch (Exception ex)
{
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
throw;
}
}
}
public class AssertionFailedException : System.Exception
{
public AssertionFailedException() : base() { }
public AssertionFailedException(string s) : base(s) { }
}
public static class Assert
{
public static void IsTrue(bool value)
{
IsTrue(value, "failed");
}
public static void IsTrue(bool value, string message)
{
if (value == false)
throw new AssertionFailedException(message ?? "failed");
}
}