Repository navigation
Closed
Milestone
Description
I am deserializing an immutable object that has parameterized constructor with [JsonConstructor] attribute.
public class DataCenter
{
[JsonConstructor]
public DataCenter(
List<DataCenterLocation> dataCenterLocations
)
{
this.DataCenterLocations = dataCenterLocations;
}
public List<DataCenterLocation> DataCenterLocations { get; }
}
Sample Json Data
{
"dataCenter": {
"dataCenterLocations": [
{
"name": "United States"
}
]
}
}
**Facing error in using immutable type with System.Text.Json **
using Microsoft.Extensions.Configuration;
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("datacenter.json", optional: false)
.Build();
// Error
var dataCenter = configuration.GetSection("dataCenter").Get<DataCenter>();
foreach (var location in dataCenter.DataCenterLocations)
{
Console.WriteLine(location.Name);
}
As mentioned in the >NET documentation the parameter names of a parameterized constructor must match the property names. Matching is case-insensitive, and the constructor parameter must match the actual property. In the above code example
[JsonConstructor]
public DataCenter(
// [JsonPropertyName("dataCenterLocations")] // Doesn't work either
List<DataCenterLocation> dataCenterLocations // Match Perfectly with Json Path dataCenter.dataCenterLocations
)
{
this.DataCenterLocations = dataCenterLocations;
}
Error Details
System.InvalidOperationException
HResult=0x80131509
Message=Cannot create instance of type 'JsonConstructorIssue.DataCenter' because parameter 'dataCenterLocations' has no matching config. Each parameter in the constructor that does not have a default value must have a corresponding config entry.
Source=Microsoft.Extensions.Configuration.Binder
StackTrace:
at Microsoft.Extensions.Configuration.ConfigurationBinder.BindParameter(ParameterInfo parameter, Type type, IConfiguration config, BinderOptions options)
at Microsoft.Extensions.Configuration.ConfigurationBinder.CreateInstance(Type type, IConfiguration config, BinderOptions options)
at Microsoft.Extensions.Configuration.ConfigurationBinder.BindInstance(Type type, BindingPoint bindingPoint, IConfiguration config, BinderOptions options)
at Microsoft.Extensions.Configuration.ConfigurationBinder.Get(IConfiguration configuration, Type type, Action`1 configureOptions)
at Microsoft.Extensions.Configuration.ConfigurationBinder.Get[T](IConfiguration configuration, Action`1 configureOptions)
at Microsoft.Extensions.Configuration.ConfigurationBinder.Get[T](IConfiguration configuration)
at Program.<Main>$(String[] args) in D:\lab\JsonConstructorIssue\JsonConstructorIssue\Program.cs:line 16
.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="7.0.0-rc.2.22472.3" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
</ItemGroup>
<ItemGroup>
<Content Include="./datacenter.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>
I created a GitHub repository to run and test the scenario.
Activity
feiyun0112 commentedon Nov 1, 2022
You must use parameter less Constructor, if you want to use NonPublic Set, do like this
navneet10sep commentedon Nov 1, 2022
Parametersless constructor is deserializing private properties using
option.BindNonPublicProperties = truebut not with the [JsonInclude] attribute as mentioned in the Documentation1 and Documentaiton2I could use this workaround for private properties, but not for immutable types. As per my understanding, An immutable type is a type of which its properties can only be set at initialization. Once an object is created, nothing can be changed anymore. So coming back to my original issue, How could I use immutable type as explained in the official documentation ?
layomia commentedon Jul 21, 2023
This is by design. To have binding succeed when there's a missing config value, specify a default value for your ctor parameter. In this case that would be
null: