Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a Converter to serialize empty strings as null values #20

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

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