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;
[JsonConverter(typeof(FloatParseHandlingConverter), FloatParseHandling.Decimal)]
public string myString { get; set; }
public List<dynamic> values { get; set; }
public class FloatParseHandlingConverter : JsonConverter
readonly FloatParseHandling floatParseHandling;
public FloatParseHandlingConverter(FloatParseHandling floatParseHandling)
this.floatParseHandling = floatParseHandling;
public override bool CanConvert(Type objectType)
throw new NotImplementedException();
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
if (reader.TokenType == JsonToken.Null)
var old = reader.FloatParseHandling;
reader.FloatParseHandling = floatParseHandling;
existingValue = existingValue ?? serializer.ContractResolver.ResolveContract(objectType).DefaultCreator();
serializer.Populate(reader, existingValue);
reader.FloatParseHandling = old;
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
throw new NotImplementedException();
public static void Test()
values = new List<object> { 1.010101010101010101010101m, 2020.202020202020202020202m, 123456789012345678.90123456m, "hello" },
Console.WriteLine("\ntest.rows[].values types: {0}.", String.Join(",", test.rows.SelectMany(r => r.values).Select(i => i.GetType().Name)));
var json = JsonConvert.SerializeObject(test, Formatting.Indented);
Console.WriteLine("\nSerialized JSON: ");
var test2 = JsonConvert.DeserializeObject<TestData>(json);
Console.WriteLine("\ntest2.rows[].values types: {0}.", String.Join(",", test2.rows.SelectMany(r => r.values).Select(i => i.GetType().Name)));
Assert.IsTrue(test2.rows.SelectMany(r => r.values).SequenceEqual(test.rows.SelectMany(r => r.values)), "values are not equal!");
Assert.IsTrue(test2.rows.SelectMany(r => r.values).Select(i => i.GetType()).SequenceEqual(test.rows.SelectMany(r => r.values).Select(i => i.GetType())), "types are not equal!");
Assert.IsTrue(!test2.rows.SelectMany(r => r.values).OfType<double>().Any(), "doubles found!");
Console.WriteLine("All tests passed.\n");
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");