Skip to content

Conversation

MatthewSteeples
Copy link

Allows these values to be excluded when IgnoreNullValues is True

Allows these values to be excluded when `IgnoreNullValues` is True
@CodeBlanch
Copy link
Member

Thanks @MatthewSteeples! I really like the idea, but I'm not sure it completely works. Check out this test:

	JsonSerializerOptions options = new JsonSerializerOptions();
	options.Converters.Add(new JsonEmptyStringToNullConverter());

	string Json = JsonSerializer.Serialize(new TestClass() { Str1 = "One", Str2 = string.Empty, Str3 = null }, options);
	Assert.AreEqual("{\"Str1\":\"One\",\"Str2\":null,\"Str3\":null}", Json);

	options = new JsonSerializerOptions();
	options.Converters.Add(new JsonEmptyStringToNullConverter());
	options.IgnoreNullValues = true;

	Json = JsonSerializer.Serialize(new TestClass() { Str1 = "One", Str2 = string.Empty, Str3 = null }, options);
	Assert.AreEqual("{\"Str1\":\"One\"}", Json); // <-- Fails
	// Actual JSON value: "{\"Str1\":\"One\",\"Str2\":null}"

	private class TestClass
	{
		public string? Str1 { get; set; }
		public string? Str2 { get; set; }
		public string? Str3 { get; set; }
	}

That second test with IgnoreNullValues=true fails. Is the expected behavior that Str2 (empty) & Str3 (null) would both be omitted?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants