using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using System.Text.Json.Nodes;
public class MyDataClass : IJsonOnDeserialized
public string [] Property1 { get; set; } = Array.Empty<string>();
public DateTime Property2 { get; set; }
public Int32 Format { get; set; }
public required Object? Value { get; set;}
void IJsonOnDeserialized.OnDeserialized()
if (Value is JsonElement e)
Value = FormatHelper.GetObjectValue(Format, e.ValueKind == JsonValueKind.String ? e.GetString() : e.GetRawText());
public enum FormatTypeBase
public class FormatHelper
public static Object? GetObjectValue(Int32 formatType, String? value)
switch ((FormatTypeBase)formatType)
case FormatTypeBase.Boolean:
result = value == "1" || value.Equals("true", StringComparison.OrdinalIgnoreCase);
case FormatTypeBase.Numeric:
result = Double.Parse(value, CultureInfo.InvariantCulture);
case FormatTypeBase.String:
throw new NotImplementedException(((FormatTypeBase)formatType).ToString());
public static void Test()
var list = new List<MyDataClass>()
new() { Property1 = new [] { "some value 1"} , Property2 = DateTime.Today.AddHours(1), Format = (int)FormatTypeBase.Boolean, Value = true },
new() { Property1 = new [] { "some value 2" }, Property2 = DateTime.Today.AddHours(2), Format = (int)FormatTypeBase.String, Value = "hello" },
new() { Property1 = new [] { "some value 3" }, Property2 = DateTime.Today.AddHours(3), Format = (int)FormatTypeBase.Numeric, Value = Math.PI },
new() { Property1 = new [] { "some value 4"} , Property2 = DateTime.Today.AddHours(4), Format = (int)FormatTypeBase.Boolean, Value = false },
var options = new JsonSerializerOptions
var json = JsonSerializer.Serialize(list, options);
var list2 = JsonSerializer.Deserialize<List<MyDataClass>>(json);
Assert.That(list.Select(i => i.Value?.GetType()).SequenceEqual(list2!.Select(i => i.Value?.GetType())), "types not identical");
var json2 = JsonSerializer.Serialize(list2, options);
Assert.AreEqual(json, json2);
Assert.That(list.SelectMany(i => i.Property1).SequenceEqual(list2!.SelectMany(i => i.Property1)));
Assert.That(list.Select(i => i.Property2).SequenceEqual(list2!.Select(i => i.Property2)));
public static void Main()
Console.WriteLine("Environment version: {0} ({1}), {2}", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , Environment.Version, Environment.OSVersion);
Console.WriteLine("System.Text.Json version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine("Failed with unhandled exception: ");