Skip to content

Commit

Permalink
Support deserialization with System.Text.Json
Browse files Browse the repository at this point in the history
  • Loading branch information
JeremySkinner committed May 26, 2022
1 parent 587931e commit eb97f54
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 3 deletions.
35 changes: 35 additions & 0 deletions src/FluentValidation.Tests/JsonSerializationTests.cs
@@ -0,0 +1,35 @@
namespace FluentValidation.Tests;

using System.Text.Json;
using Results;
using Xunit;

public class JsonSerializationTests {

[Fact]
public void SystemTextJson_deserialization_should_be_consistent_with_newtonsoft() {
var validationResult = new ValidationResult {
Errors = {
new ValidationFailure("MyProperty1", "Invalid MyProperty1"),
new ValidationFailure("MyProperty2", "Invalid MyProperty2"),
new ValidationFailure("MyProperty3", "Invalid MyProperty3")
}
};
// System.Text.Json
var serialized1 = JsonSerializer.Serialize(validationResult);
var deserialized1 = JsonSerializer.Deserialize<ValidationResult>(serialized1);

// Newtonsoft.Json
var serialized2 = Newtonsoft.Json.JsonConvert.SerializeObject(validationResult);
var deserialized2 = Newtonsoft.Json.JsonConvert.DeserializeObject<ValidationResult>(serialized2);

Assert.NotNull(deserialized1);
Assert.Equal(deserialized1.IsValid, deserialized2.IsValid);
Assert.Equal(deserialized1.Errors.Count, deserialized2.Errors.Count);

for (var i = 0; i < deserialized1.Errors.Count; i++) {
Assert.Equal(deserialized1.Errors[i].PropertyName, deserialized2.Errors[i].PropertyName);
Assert.Equal(deserialized1.Errors[i].ErrorMessage, deserialized2.Errors[i].ErrorMessage);
}
}
}
3 changes: 2 additions & 1 deletion src/FluentValidation/Results/ValidationFailure.cs
Expand Up @@ -25,7 +25,8 @@ namespace FluentValidation.Results {
/// </summary>
[Serializable]
public class ValidationFailure {
private ValidationFailure() {

public ValidationFailure() {

}

Expand Down
11 changes: 9 additions & 2 deletions src/FluentValidation/Results/ValidationResult.cs
Expand Up @@ -26,7 +26,7 @@ namespace FluentValidation.Results {
/// </summary>
[Serializable]
public class ValidationResult {
private readonly List<ValidationFailure> _errors;
private List<ValidationFailure> _errors;

/// <summary>
/// Whether validation succeeded
Expand All @@ -36,7 +36,14 @@ public class ValidationResult {
/// <summary>
/// A collection of errors
/// </summary>
public List<ValidationFailure> Errors => _errors;
public List<ValidationFailure> Errors {
get => _errors;
#if NETSTANDARD2_0_OR_GREATER
set => _errors = value ?? throw new ArgumentNullException(nameof(value));
#else
init => _errors = value ?? throw new ArgumentNullException(nameof(value));
#endif
}

public string[] RuleSetsExecuted { get; internal set; }

Expand Down

0 comments on commit eb97f54

Please sign in to comment.