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 Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
// // https://stackoverflow.com/questions/46293907/create-custom-json-converter-using-newtonsoft-json-library-to-get-additional-dat
class AbcDTO
{
public AbcDTO() { this.AdditionalData = new Dictionary<string, object>(); }
public string Prop1 { get; set; }
public string Prop2 { get; set; }
//public List<AdditionalProperty> AdditionalData { get; set; }
[JsonExtensionData]
public Dictionary<string, object> AdditionalData { get; private set; }
}
class TestClass
{
public static void Test()
{
var json = GetJson();
var dto = JsonConvert.DeserializeObject<AbcDTO>(json);
var json2 = JsonConvert.SerializeObject(dto, Formatting.Indented);
Console.WriteLine(json2);
// Assert all the values are primitives.
Console.WriteLine(string.Format("Dictionary value types: {0}", String.Join(",", dto.AdditionalData.Values.Select(v => v == null ? "null" : v.GetType().ToString()))));
Assert.IsTrue(!dto.AdditionalData.Values.OfType<JToken>().Any(), "Some values were of type JToken!");
Console.WriteLine("No dictionary values were of type JToken.");
}
static string GetJson()
{
var json = @"{
""Prop1"": ""Val1"",
""Prop2"": ""Val2"",
""AdditionalProp3"": ""Val3"",
""AdditionalProp4"": ""Val4"",
""AdditionalProp5"": 1010101,
""AdditionalProp6"": true,
""AdditionalProp7"": null,
""AdditionalProp8"": ""2012-03-19T07:22Z"",
}
";
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");
}
}