CSharp · Console
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.ComponentModel.DataAnnotations;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using NUnit.Framework; // Throws NUnit.Framework.AssertionException
//https://stackoverflow.com/questions/76558333/jsonconvert-deserializeobject-throwing-error-after-adding-addnewtonsoftjson
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)
: null;
public override void WriteJson(JsonWriter writer, ValidationResult value, JsonSerializer serializer) =>
serializer.Serialize(writer, new DTO(value.ErrorMessage, value.MemberNames));
}
public class Mymodel
{
public List<ValidationResult> ValidationResults { get; } = new ();
}
class TestClass
{
public static void Test()
{
var model = new Mymodel
{
ValidationResults =
{
new ("message1"),
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);
Console.WriteLine(res);
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 class Program
{
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();
try
{
TestClass.Test();
}
catch (Exception ex)
{
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
throw;
}
}
}