runtime icon indicating copy to clipboard operation
runtime copied to clipboard

[JsonSerializer] Relax restrictions on ctor param type to immutable property type matching where reasonable

Open JSkimming opened this issue 6 years ago • 76 comments

Description

I'm trying to deserialise an object from a json string. In this case the constructor allows a nullable value type as the parameter, setting a non-null property (defaulting if null).

I expect (since it is the behaviour with Newtonsoft.Json) the serializer to handle compatible constructor and bound value type properties (or fields) where the only difference is one is nullable.

The following demonstrates the issue:

public class Example
{
    public Example(Guid? aGuid) => AGuid = aGuid ?? Guid.Empty;
    public Guid AGuid { get; }
}

Example original = new Example(Guid.NewGuid());

// Works with Newtonsoft.Json.
string withJsonNet = JsonConvert.SerializeObject(original);
JsonConvert.DeserializeObject<Example>(withJsonNet);

// Fails with System.Text.Json.
string withSystemTextJson = System.Text.Json.JsonSerializer.Serialize(original);
System.Text.Json.JsonSerializer.Deserialize<Example>(withSystemTextJson);

An InvalidOperationException is thrown from the method System.Text.Json.JsonSerializer.Deserialize :

System.InvalidOperationException: Each parameter in constructor 'Void .ctor(System.Nullable`1[System.Guid])' on type 'Example' must bind to an object property or field on deserialization. Each parameter name must match with a property or field on the object. The match can be case-insensitive.

Configuration

I'm building an ASP.NET Core app targeting netcoreapp3.1, and using version 5.0.0-rc.2.20475.5 of System.Text.Json. I'm also using version 12.0.3 of Newtonsoft.Json.

Other information

Stack Trace:

System.InvalidOperationException: Each parameter in constructor 'Void .ctor(System.Nullable`1[System.Guid])' on type 'Example' must bind to an object property or field on deserialization. Each parameter name must match with a property or field on the object. The match can be case-insensitive.
   at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_ConstructorParameterIncompleteBinding(ConstructorInfo constructorInfo, Type parentType)
   at System.Text.Json.Serialization.Converters.ObjectWithParameterizedConstructorConverter`1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
   at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
   at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.JsonSerializer.ReadCore[TValue](JsonConverter jsonConverter, Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.JsonSerializer.ReadCore[TValue](Utf8JsonReader& reader, Type returnType, JsonSerializerOptions options)
   at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, Type returnType, JsonSerializerOptions options)
   at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options)
   at <custom code>

JSkimming avatar Nov 09 '20 21:11 JSkimming

Why make the constructor parameter nullable? The AGuid property is non-nullable which means that null will never be serialized. Are you expecting null JSON tokens to bind with the parameter on deserialization? Where would this JSON come from?

layomia avatar Nov 12 '20 18:11 layomia

Thanks for the reply @layomia

To present a minimal use-case the example is intentionally trivial.

My situation is rather more complex. We have several scenarios where having the parameter as nullable was desirable (and worked well using Newtonsoft.Json), some of which we can, and have, resolved by making the parameter non-nullable.

But there are other scenarios where a nullable parameter with a non-nullable property is still preferred. One being where we have an unknown number of legacy objects that are serialised to a store with null values. The use-cases have since been updated where new instances are not serialised with null, but we still want to support the de-serialization of the legacy objects.

If we had been using System.Text.Json at the time, we probably would have implemented the solution differently, but as I highlighted above Newtonsoft.Json worked.

Hope the context helps.

Ultimately though, this is a difference in behaviour with Newtonsoft.Json. It looks like you are trying to resolve edge cases in to make System.Text.Json "the standard JSON stack for .NET." (See Issue #43620). And this is one such edge case.

JSkimming avatar Nov 13 '20 07:11 JSkimming

From @https://github.com/NN--- in https://github.com/dotnet/runtime/issues/46480:

Description

    public class Q
    {
        [JsonConstructor]
        public Q(int? x)
        {
            if (x is null) throw new Exception();
            X = x.Value;
        }
        
        public int X { get; }
    }

Given string:

var str = JsonSerializer.Deserialize<Q>("{\"X\":123}" ");

It is deserialized fine with Newtonsoft, but not with System.Text. The reason is that constructor parameter type is int? while the property has type of int. Newtonsoft doesn't validate it, giving an option to do anything in the constructor.

There are possible workarounds but they are not as simple as the original code:

Make property private and add a public non nullable:

    public class Q
    {
        [JsonConstructor]
        public Q(int? x)
        {
            if (x is null) throw new Exception();
            X = x.Value;
        }

        public int? X { get; }

        [JsonIgnore]
        public int NonNullableX => X!.Value;
    }

Annotate nullable as non nullable, however it requires explicit call to Value.:

    public class Q
    {
        [JsonConstructor]
        public Q(int? x)
        {
            if (x is null) throw new Exception();
            X = x.Value;
        }

        [DisallowNull][NotNull]
        public int? X { get; }
    }

Configuration

Regression?

Not a regression.

Other information

layomia avatar Jan 25 '21 17:01 layomia

We could look into relaxing the matching algorithm here if it proves to be unwieldy. The workaround here is to refactor the POCO code slightly to make the property type and the constructor parameter type the same. This issue will not be treated as high priority until a blocked and non-trivial scenario is provided.

layomia avatar Jan 25 '21 17:01 layomia

Deserializing JSON into an object that can be bound to WPF\XAML is likely very common place and converting an incoming IEnumerable into a observable collection that XAML can use is also likely common.

Not supporting this limits System.Text.Json's use with an XAML\WPF\UWP apps.

GabeDeBacker avatar Jan 25 '21 19:01 GabeDeBacker

This issue will not be treated as high priority until a blocked and non-trivial scenario is provided.

@layomia As I explained, the example is trivial to present a minimal use-case. I also went on to explain the non-trivial scenario:

we have an unknown number of legacy objects that are serialised to a store with null values. The use-cases have since been updated where new instances are not serialised with null, but we still want to support the de-serialization of the legacy objects.

We are also blocked. Our workaround is to stick with Newtonsoft.Json.

JSkimming avatar Jan 25 '21 21:01 JSkimming

Thanks for the responses and expanding on the importance here. There are definitely various scenarios where loosening the matching restrictions is helpful. We can address this in the .NET 6.0 release.

layomia avatar Jan 25 '21 23:01 layomia

From @GabeDeBacker in https://github.com/dotnet/runtime/issues/47422#:

Description

System.Text.Json deserialization requires that a property type match the constructor type for immutable properties even though the constructor can convert the type.

This is a simple example of a class that will convert an incoming IEnumerable to a ReadOnlyObservableCollection for XAML binding.

        [JsonConstructor]
        public Logger(IEnumerable<LogEntry> entries)
        {
            this.Entries = new ReadOnlyObservableCollection<LogEntry>(this.entries);
        }

        public ReadOnlyObservableCollection<LogEntry> Entries { get; }

When desrializing from JSON, this fails.

Changing the property to be IEnumerable allows the deserialization to succeed, but that means I would need to add “another” property to this class for XAML binding to work. (Which is what this class is used for). The below just doesn’t seem right and was not something I had to do when using NewtonSoft

        public Logger(IEnumerable<LogEntry> entries)
        {
            this.Entries = entries;
            this.ObersvableEntries = new ReadOnlyObservableCollection<LogEntry>(this.entries);
        }

        public IEnumerable<LogEntry> Entries { get; }

        [JsonIgnore]
        public ReadOnlyObservableCollection<LogEntry> ObersvableEntries { get; }

layomia avatar Jan 26 '21 00:01 layomia

Today, we expect an exact match between the constructor parameter type and the immutable property type. This is too restrictive in two major cases:

  • mapping nullable value-type ctor args to immutable properties of a non-nullable version of the type, as described in the description above https://github.com/dotnet/runtime/issues/44428#issue-739367850:

    public class Example
    {
        public Guid AGuid { get; }
        public Example(Guid? aGuid) => AGuid = aGuid ?? Guid.Empty;
    }
    
  • scenarios where a reasonable conversion can be made between the ctor param type and the destination immutable property type, for example the scenario in https://github.com/dotnet/runtime/issues/44428#issuecomment-767195623:

    public class Logger
    {
        public ReadOnlyObservableCollection<LogEntry> Entries { get; }
        public Logger(IEnumerable<LogEntry> entries) => Entries = new ReadOnlyObservableCollection<LogEntry>(entries);
    }
    

We can loosen the restriction and support these scenarios by checking that the ctor parameter is assignable from the immutable property type. This new algorithm is in accordance with the serializer always round-tripping (i.e being able to deserialize whatever we serialize), and maintains a high probability that the incoming JSON is compatible with the target ctor param. This is important to avoid unintentional data loss.

If there are more reasonable scenarios that will not be satisfied with this proposal, we can evaluate them and perhaps adjust further.

layomia avatar Jan 26 '21 00:01 layomia

We can also, or alternatively, consider a property on JsonConstructorAttribute, that indicates no restriction between the ctor parameter type and the immutable property type. This would allow them to be two arbitrarily different types, basically an "I know what I'm doing mode". It would still be required for their CLR names to match.

/// <summary>
/// When placed on a constructor, indicates that the constructor should be used to create
/// instances of the type on deserialization.
/// </summary>
[AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false)]
public sealed class JsonConstructorAttribute : JsonAttribute
{
    /// <summary>
    /// When <see cref="true" />, indicates that no restriction should be placed on the types of a constructor
    /// parameter and a property when there is a case-insensitive match between their names.
    /// </summary>
    public bool UseRelaxedPropertyMatching { get; set; }

    /// <summary>
    /// Initializes a new instance of <see cref="JsonConstructorAttribute"/>.
    /// </summary>
    public JsonConstructorAttribute() { }
}

A global option can be considered as well, to support non-owned types where we can't decorate with an attribute:

public sealed class JsonSerializerOptions
{
    /// <summary>
    /// When <see cref="true" />, indicates that no restriction should be placed on the types of a constructor
    /// parameter and a property when there is a case-insensitive match between their names.
    /// </summary>
    public bool ConstructorUseRelaxedPropertyMatching { get; set; }
}

All of this design assumes that there will always be a requirement that every constructor parameter binds to an object property, per the original spec for this feature: https://github.com/dotnet/runtime/pull/33095.

layomia avatar Jan 26 '21 01:01 layomia

@layomia - Implementing either (or both) of what you mentioned above (the JsonConstructorAttribute argument or is the constructor argument assignable from the property type) would be great additions! Thanks for the conversation

GabeDeBacker avatar Jan 26 '21 02:01 GabeDeBacker

We can also, or alternatively, consider a property on JsonConstructorAttribute, that indicates no restriction between the ctor parameter type and the immutable property type. This would allow them to be two arbitrarily different types, basically an "I know what I'm doing mode". It would still be required for their CLR names to match.

We would likely still need to support the "mapping nullable value-type ctor args to immutable properties of a non-nullable version of the type" case by default - https://github.com/dotnet/runtime/issues/44428#issue-739367850.

layomia avatar Jan 26 '21 13:01 layomia

Co-assigning @GabeDeBacker to provide the implementation for this feature, as discussed offline.

layomia avatar Jan 27 '21 17:01 layomia

I did find an example of where a property type is not assignable from the constructor argument type. You cannot construct a SecureString from a string.

public class ClassThatStoresSecureStrings
{
    using System;
    using System.Security;

   public ClassThatStoresSecureStrings(string userId, string password)
   {
            // This code repeats for password.
            this.UserId = new SecureString();
            foreach (var ch in userId)
            {
                this.UserId.AppendChar(ch);
            }

            this.UserId.MakeReadOnly();
   }

   public SecureString UserId { get; }
   public SecureString Password {get; }
}

GabeDeBacker avatar Mar 04 '21 17:03 GabeDeBacker

From @terrajobst in https://github.com/dotnet/runtime/issues/53303:

I have the following class:

public sealed class CrawledAreaOwnerEntry
{
    public CrawledAreaOwnerEntry(string area, string lead, IEnumerable<string> owners)
    {
        Area = area;
        Lead = lead;
        Owners = owners.ToArray();
    }

    public string Area { get; }
    public string Lead { get; }
    public IReadOnlyList<string> Owners { get; }
}

When deserializing it, I get the following exception:

System.InvalidOperationException: Each parameter in constructor 'Void .ctor(System.String, System.String, System.Collections.Generic.IEnumerable`1[System.String])' on type 
'IssueDb.CrawledAreaOwnerEntry' must bind to an object property or field on deserialization. Each parameter name must match with a property or field on the object.
The match can be case-insensitive.
   at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_ConstructorParameterIncompleteBinding(ConstructorInfo constructorInfo, Type parentType)
   at System.Text.Json.Serialization.Converters.ObjectWithParameterizedConstructorConverter`1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
   at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
   at System.Text.Json.Serialization.Converters.DictionaryDefaultConverter`3.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, TCollection& value)
   at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
   at System.Text.Json.JsonPropertyInfo`1.ReadJsonAndSetMember(Object obj, ReadStack& state, Utf8JsonReader& reader)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
   at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
   at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.JsonSerializer.ReadCore[TValue](JsonReaderState& readerState, Boolean isFinalBlock, ReadOnlySpan`1 buffer, JsonSerializerOptions options, ReadStack& state, JsonConverter converterBase)
   at System.Text.Json.JsonSerializer.ReadAsync[TValue](Stream utf8Json, Type returnType, JsonSerializerOptions options, CancellationToken cancellationToken)
   at IssueDb.Crawling.CrawledRepo.LoadAsync(String path) in /home/runner/work/issuesof.net/issuesof.net/src/IssueDb/Crawling/CrawledRepo.cs:line 43

It seems the serializer requires the types of the properties to be identical to the parameter. That feels overly restrictive to me; it seems we should only require that the property type is assignable to the parameter type.

layomia avatar May 27 '21 15:05 layomia

Unassigning @GabeDeBacker https://github.com/dotnet/runtime/pull/47661#issuecomment-856936994.

layomia avatar Jun 08 '21 17:06 layomia

We couldn't get to this in .NET 6.0 but can consider for .NET 7.

layomia avatar Jul 23 '21 00:07 layomia

Reposting my reply to #45190 (@layomia asked me to repost it here)

This is my use-case for wanting support for private primary-constructors and multiple primary-constructors, and partial mapping between properties and ctor parameters:


I know System.Text.Json won't invoke private members by default, but I'm surprised and disappointed that we cannot explicitly denote private constructors with [JsonConstructor].

Ideally I'd like to reuse the same DTO types in Newtonsoft.Json and System.Text.Json contexts (with suitable using JsonPropertyAttribute = System.Text.Json.Serialization.JsonPropertyNameAttribute in #if USE_STJ at the top of the .cs file), however my projects tend to use primary-constructors which STJ doesn't support, so I can't use the above trick just yet.

  • [ ] Allow [JsonConstructor] with private constructors, even when a public constructor is available.
    • This is essential for cases where a type has different constructors for different states, with per-state validation logic (for an example, see my class SqlDbTypeRef in the expanding region below). Exposing a public constructor that has parameters for all properties would allow consumers to unwittingly circumvent the validation rules - and requiring us to reimplementing the validation logic in this new constructor is not endearing me to use STJ over NJ.
  • [ ] Allow [JsonPropertyName] on constructor parameters and use JsonPropertyNameAttribute.Name to map them to C# properties' JsonPropertyNameAttribute.Name instead of their C# property names.
    • This make it easier to write DTOs that are more resilient to unintentional symbol renames when refactoring - especially as Visual Studio's C# Refactor-Rename tool does not currently rename constructor parameters that are assigned to POCO properties.
    • Allowing explicit JSON property names on ctor parameters also allows us to tweak serialization vs. deserialization logic without needing too much effort.
    • A use-case for this is when you want the same DTO to intentionally ignore or drop certain properties when deserializing but still serialize them and you're using code-gen or T4 to generate DTOs and having to use custom logic in the ctor is just too much effort.
  • [ ] Allow partial [JsonConstructor] parameter-to-property mapping.
    • This is useful when the private [JsonConstructor] is also used by a public static factory method and additional details are routed through there but would not come from JSON - so the constructor has more parameters than JSON properties.

For example, I have a class that represents a SqlDbType with length, precision, and scale parameters - this is what I currently have working with Newtonsoft.Json:


Click to expand!
public partial class SqlDbTypeRef
{
	/// <summary>For <see cref="System.Data.SqlDbType"/> types without parameters.</summary>
	/// <exception cref="ArgumentException">When the <paramref name="dbType"/> value used requires length, precision, or scale parameter values.</exception>
	public SqlDbTypeRef( SqlDbType dbType )
	{
		SqlDbTypeParameters p = SqlDbTypeExtensions.GetParameters( dbType );
		if( p == SqlDbTypeParameters.None )
		{
			Int16? length = null;
			if( SqlDbTypeExtensions.HasImplicitLength( dbType, out Int16 implicitLength ) ) length = implicitLength;

			this.SqlDbType = dbType;
			this.Length    = length;
			this.Precision = null;
			this.Scale     = null;
		}
		else
		{
			throw new ArgumentException( message: "SqlDbType.{0} is parameterized: {1}".Fmt( dbType, p ), paramName: nameof(dbType) );
		}
	}
		
	/// <summary>For <see cref="SqlDbType.Binary"/>, <see cref="SqlDbType.VarBinary"/>, <see cref="SqlDbType.Char"/>, <see cref="SqlDbType.NChar"/>, <see cref="SqlDbType.NVarChar"/>, <see cref="SqlDbType.VarChar"/>.</summary>
	public SqlDbTypeRef( SqlDbType dbType, Int16 length )
	{
		SqlDbTypeParameters p = SqlDbTypeExtensions.GetParameters( dbType );
		if( p == SqlDbTypeParameters.Length )
		{
			this.SqlDbType = dbType;
			this.Length    = length;
			this.Precision = null;
			this.Scale     = null;
		}
		else
		{
			throw new ArgumentException( message: "SqlDbType.{0} requires {1}".Fmt( dbType, p ), paramName: nameof(dbType) );
		}
	}

	/// <summary>For <see cref="SqlDbType.DateTime2"/>, <see cref="SqlDbType.DateTimeOffset"/>, <see cref="SqlDbType.Float"/>.</summary>
	public SqlDbTypeRef( SqlDbType dbType, Byte precision )
	{
		SqlDbTypeParameters p = SqlDbTypeExtensions.GetParameters( dbType );
		if( p == SqlDbTypeParameters.Precision )
		{
			this.SqlDbType = dbType;
			this.Length    = null;
			this.Precision = precision;
			this.Scale     = null;
		}
		else
		{
			throw new ArgumentException( message: "SqlDbType.{0} requires {1}".Fmt( dbType, p ), paramName: nameof(dbType) );
		}
	}

	/// <summary>For <see cref="SqlDbType.Decimal"/>.</summary>
	public SqlDbTypeRef( SqlDbType dbType, Byte precision, Byte scale )
	{
		SqlDbTypeParameters p = SqlDbTypeExtensions.GetParameters( dbType );
		if( p == SqlDbTypeParameters.PrecisionAndScale )
		{
			this.SqlDbType = dbType;
			this.Length    = null;
			this.Precision = precision;
			this.Scale     = scale;
		}
		else
		{
			throw new ArgumentException( message: "SqlDbType.{0} requires {1}".Fmt( dbType, p ), paramName: nameof(dbType) );
		}
	}

	[JsonConstructor]
	private SqlDbTypeRef(
		[JsonProperty( "type"   )] SqlDbType dbType,
		[JsonProperty( "length" )] Int16?    length,
		[JsonProperty( "precision" )] Byte?     precision,
		[JsonProperty( "scale"  )] Byte?     scale
	)
	{
		this.SqlDbType = dbType;
		this.Length    = length;
		this.Precision = precision;
		this.Scale     = scale;
	}

	[JsonProperty( "type" )]
	public SqlDbType SqlDbType { get; }

	[JsonProperty( "length", NullValueHandling = NullValueHandling.Ignore )]
	public Int16?    Length    { get; }
		
	[JsonProperty( "precision", NullValueHandling = NullValueHandling.Ignore )]
	public Byte?     Precision { get; }
		
	[JsonProperty( "scale", NullValueHandling = NullValueHandling.Ignore )]
	public Byte?     Scale     { get; }
}

daiplusplus avatar Aug 18 '21 01:08 daiplusplus

@layomia I landed here from https://github.com/dotnet/runtime/issues/59804

I am not sure if I understand correctly your proposal, so I try to rephrase it.

When I apply JsonConstructorAttribute, I would like the deserialization to just match the signature of the constructor marked with JsonConstructorAttribute with zero requirements over the properties.

  • Use that constructor even if its visibility is private/internal/whatever
  • Match the parameter types/names according to the json being deserialized
  • It will be up to the developer to initialize the object state (properties/fields)

Are you going in this direction?

Thank you!

raffaeler avatar Oct 29 '21 11:10 raffaeler

@raffaeler

Use that constructor even if its visibility is private/internal/whatever

Yes this is an enhancement we plan to make as part of this work. In the source-gen case, only public and internal ctors can be used, so the generator will issue a diagnostic if the attribute is placed on a ctor that is not accessible to the generated code.

Match the parameter types/names according to the json being deserialized

It will be up to the developer to initialize the object state (properties/fields)

Given further feedback from scenarios like https://github.com/dotnet/runtime/issues/44428#issuecomment-900743092, I'm inclined to have the serializer perform no validation on ctor parameter/property binding wrt to names and data type, and just have the user perform whatever validation they need within the constructor, or using one of the deserialization callbacks (IJsonOnDerializing, IJsonOnDeserialized)

layomia avatar Nov 22 '21 23:11 layomia