Skip to content

Commit

Permalink
Add simpler api to ignore default value in WriteMember (#1236)
Browse files Browse the repository at this point in the history
  • Loading branch information
SimonCropp authored Jul 2, 2024
1 parent 6678d09 commit 125d23f
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<Project>
<PropertyGroup>
<NoWarn>CS1591;CS0649;xUnit1026;xUnit1013;CS1573;VerifyTestsProjectDir;VerifySetParameters;PolyFillTargetsForNuget</NoWarn>
<Version>25.0.4</Version>
<Version>25.1.0</Version>
<ImplicitUsings>enable</ImplicitUsings>
<LangVersion>preview</LangVersion>
<AssemblyVersion>1.0.0</AssemblyVersion>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"withDefault": {},
"withNonDefault": {
"Name": "Value"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
withDefault: {},
withNonDefault: {
Name: Value
}
}
27 changes: 27 additions & 0 deletions src/Verify.Tests/Serialization/SerializationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3751,6 +3751,33 @@ class ConverterTarget
public string Name { get; set; } = null!;
}

[Fact]
public Task WithConverterIgnoreDefault() =>
Verify(
new
{
withDefault = new ConverterTarget
{
Name = "Ignore"
},
withNonDefault = new ConverterTarget
{
Name = "Value"
},
})
.AddExtraSettings(_ => _.Converters.Add(new ConverterIgnoreDefault()));

class ConverterIgnoreDefault :
WriteOnlyJsonConverter<ConverterTarget>
{
public override void Write(VerifyJsonWriter writer, ConverterTarget target)
{
writer.WriteStartObject();
writer.WriteMember(target, target.Name, "Name", "Ignore");
writer.WriteEnd();
}
}

[Fact]
public Task WithRecursiveConverter() =>
Verify(new RecursiveConverterTarget())
Expand Down
20 changes: 20 additions & 0 deletions src/Verify/Serialization/VerifyJsonWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,26 @@ public override void WriteValue(Guid value)
WriteRawValueWithScrubbers(buffer);
}


/// <summary>
/// Writes a property name and value while respecting other custom serialization settings.
/// </summary>
public void WriteMember<T>(object target, T? value, string name, T defaultIgnore)
where T : IEquatable<T?>
{
if (value is null)
{
return;
}

if (value.Equals(defaultIgnore))
{
return;
}

WriteMember(target, value, name);
}

/// <summary>
/// Writes a property name and value while respecting other custom serialization settings.
/// </summary>
Expand Down

0 comments on commit 125d23f

Please sign in to comment.