Skip to content

Configuration Json provider loads null values as empty string #40827

Closed
@alefranz

Description

@alefranz

Description

Configuration Json provider loads null values as empty string.
I understand that other providers like the environment variables one do not support to add null, however I don't think this should prevent the json provider to do the expected thing of preserving null.
Also as the enviornment variables provider supports adding both a value and children for a key which the json one doesn't so I don't think that a limitation of one provider should affect the others.

One important consideration is that changing this will mean that null values will return false for Exists(), as the Exists() method is a misnomer, as the outcome is "not empty", while currently given null is converted to empty string, Exists() is returning true.

/// <summary>
/// Determines whether the section has a <see cref="IConfigurationSection.Value"/> or has children
/// </summary>
public static bool Exists(this IConfigurationSection section);

Repro

config.json
{
    "g": null,
}
Program.cs
using System;
using Microsoft.Extensions.Configuration;

namespace Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                .AddJsonFile("config.json")
                .Build();

            Console.WriteLine("{");

            Console.WriteLine("\t" + GetString(config.GetSection("g"));

            Console.WriteLine("}");
        }

        private static string GetString(IConfigurationSection configurationSection) => GetString(configurationSection.Key, configurationSection.Value);
        
        private static string GetString(string key, string value) => $"\"{key}\":" + (value is null ? "null" : $"\"{value}\"");
    }
}
Sample.csproj
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="5.0.0-preview.7.20364.11" />
  </ItemGroup>

  <ItemGroup>
    <Content Include="config.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>

</Project>

Expected output

{
    "g": null
}

Actual output

{
    "g": ""
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions