Skip to content

Commit

Permalink
fix: Default JSON serializer instance is not affected by custom globa…
Browse files Browse the repository at this point in the history
…l settings for default value handling.

Fixes #2609
  • Loading branch information
amanda-tarafa committed Nov 15, 2023
1 parent c00ff39 commit a9fb5df
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,8 @@ public static JsonSerializerSettings CreateDefaultSettings() =>
{
NullValueHandling = NullValueHandling.Ignore,
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
ContractResolver = new NewtonsoftJsonContractResolver()
ContractResolver = new NewtonsoftJsonContractResolver(),
DefaultValueHandling = DefaultValueHandling.Include,
};

/// <inheritdoc/>
Expand Down
31 changes: 31 additions & 0 deletions Src/Support/Google.Apis.Tests/Json/NewtonsoftJsonSerializerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,37 @@ public void CustomInstanceAvoidingDateParsing()
Assert.IsType<string>(value);
}

/// <summary>
/// Regression test for https://github.com/googleapis/google-api-dotnet-client/issues/2609.
/// <see cref="TypeWithOverridableField"/> mimics Google.Apis.Auth.OAuth2.Responses.
/// </summary>
[Fact]
public void DefaultInstance_DefaultValueHandling_IsNotCustom()
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
// If this settings have effect on the default serializer instance, then
// TypeWithOverridableField.FieldOverride will be set to null which means
// that Field will also be set to null regardles of it's value on the JSON text.
DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate
};

var text = @"{""field"":""field_value""}";
var value = NewtonsoftJsonSerializer.Instance.Deserialize<TypeWithOverridableField>(text);
Assert.Equal("field_value", value.Field);
}

public class TypeWithOverridableField
{
[JsonProperty("field")]
public string Field { get; set; }

[JsonProperty("field_override")]
#pragma warning disable IDE0051 // Remove unused private members. See the test comment.
private string FieldOverride { set => Field = value; }
#pragma warning restore IDE0051 // Remove unused private members
}

[Fact]
public void DefaultInstanceSerializesTwoETags()
{
Expand Down

0 comments on commit a9fb5df

Please sign in to comment.