using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
public class ValidationResultConverter : JsonConverter<ValidationResult>
record DTO(string ErrorMessage, IEnumerable<string> MemberNames);
public override ValidationResult ReadJson(JsonReader reader, Type objectType, ValidationResult existingValue, bool hasExistingValue, JsonSerializer serializer) =>
serializer.Deserialize<DTO>(reader) is {} dto
? new ValidationResult(dto.ErrorMessage, dto.MemberNames)
public override void WriteJson(JsonWriter writer, ValidationResult value, JsonSerializer serializer) =>
serializer.Serialize(writer, new DTO(value.ErrorMessage, value.MemberNames));
public List<ValidationResult> ValidationResults { get; } = new ();
public static void Test()
new ("message2", new [] { "member name 2.1", "member name 2.2" }),
var settings = new JsonSerializerSettings
Converters = { new ValidationResultConverter() },
var res = JsonConvert.SerializeObject(model, Formatting.Indented, settings);
var validationResponse = JsonConvert.DeserializeObject<Mymodel>(res, settings);
Assert.That(model.ValidationResults.Select(v => v.ErrorMessage).SequenceEqual(validationResponse.ValidationResults.Select(v => v.ErrorMessage)));
Assert.That(model.ValidationResults.SelectMany(v => v.MemberNames).SequenceEqual(validationResponse.ValidationResults.SelectMany(v => v.MemberNames)));
Assert.That(res == JsonConvert.SerializeObject(validationResponse, Formatting.Indented, settings));
public static void Main()
Console.WriteLine("Environment version: {0} ({1}), {2}", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , Environment.Version, Environment.OSVersion);
Console.WriteLine("{0} version: {1}", typeof(JsonSerializer).Namespace, typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine("Failed with unhandled exception: ");