Skip to content

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

Open

Description

@JSkimming

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>

Activity

  1. added
    untriaged
    on Nov 9, 2020
  2. layomia commented on Nov 12, 2020

    @layomia
    Contributor

    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?

  3. removed
    untriaged
    on Nov 12, 2020
  4. added this to the Future milestone on Nov 12, 2020
  5. JSkimming commented on Nov 13, 2020

    @JSkimming
    Author

    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.

  6. layomia commented on Jan 25, 2021

    @layomia
    Contributor

    From @https://github.com/NN--- in #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

  7. layomia commented on Jan 25, 2021

    @layomia
    Contributor

    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.

  8. GabeDeBacker commented on Jan 25, 2021

    @GabeDeBacker

    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.

  9. JSkimming commented on Jan 25, 2021

    @JSkimming
    Author

    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.

  10. layomia commented on Jan 25, 2021

    @layomia
    Contributor

    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.

  11. self-assigned this
    on Jan 25, 2021
  12. modified the milestones: Future, 6.0.0 on Jan 25, 2021
  13. added
    enhancement
    on Jan 25, 2021
  14. 69 remaining items

  15. eiriktsarpalis commented on Aug 7, 2024

    @eiriktsarpalis
    Member

    While the existing restriction is well-intentioned in that it ensures that users don't write models that are not round-tripable, it's pretty painful in the cases where it doesn't work. We could try to make the matching algorithm smarter so that similarly shaped types are considered equivalent, however I doubt this would be addressing the problem completely. There are many cases where a mismatch could be intentional (e.g. because the type is only used for deserialization).

    I think the best course of action is to expose a switch that disables constructor parameter matching for a given type, or globally.

    API Proposal

    namespace System.Text.Json.Serialization;
    
    public partial class JsonConstructorAttribute
    {
    +   public bool DisableParameterMatching { get; set; }
    }

    And for the global variant:

    namespace System.Text.Json;
    
    public partial class JsonSerializerOptions
    {
    +   public bool DisableConstuctorParameterMatching { get; set; }
    }
    
    namespace System.Text.Json.Serialization;
    
    public partial class JsonSourceGenerationOptionsAttribute
    {
    +   public bool DisableConstuctorParameterMatching { get; set; }
    }

    API Usage

    JsonSerializer.Deserialize<MyPoco>("""{"x" : 1, "y" : 2 }"""); // Succeeds
    
    public class MyPoco
    {
         [JsonConstructor(DisableParameterMatching = true)]
         public MyPoco(int x, int y) { }
    }
  16. raffaeler commented on Aug 7, 2024

    @raffaeler

    @eiriktsarpalis This was indeed the initial proposal:
    Please ensure to add a global option in the JsonSerializerOptions (the proposed property was ConstructorUseRelaxedPropertyMatching ) so that we can use it without attribute decoration.
    Please also consider this comment.

  17. terrajobst commented on Aug 7, 2024

    @terrajobst
    Contributor

    @eiriktsarpalis

    While the existing restriction is well-intentioned in that it ensures that users don't write models that are not round-tripable

    Could you explain what this means? Naively, I'd say that as long as there is an implicit conversion from the property type to the parameter type round-tripping is guaranteed by the constructor. For example, if the parameter is nullable and the property isn't or if the parameter is IEnumerable<T> but the property is T[] or ImmutableArray<T>. There is, of course, cost to check for that, but the check would only execute where it currently fails the type comparison checks, so it won't regress the most common cases.

    Personally, I'd hate to see an opt-in for this feature. I guess an opt-out would be reasonable, but it seems weird given that the alternative is throwing an error.

  18. eiriktsarpalis commented on Aug 8, 2024

    @eiriktsarpalis
    Member

    While the existing restriction is well-intentioned in that it ensures that users don't write models that are not round-tripable

    Could you explain what this means? Naively, I'd say that as long as there is an implicit conversion from the property type to the parameter type round-tripping is guaranteed by the constructor.

    I think it's reasonable to relax the restriction on the basis of a type relationship (allow constructor parameters that are assignable/convertible from the corresponding property parameter, on the basis of the principle that valid deserialization inputs should be a superset of the valid serialization outputs). My point though is that the problem extends beyond the narrow scope of subtyping, for example one might reasonably expect that this is a valid model:

    public class MyPoco(IEnumerable<IEnumerable<string>> tokens)
    {
        public ImmutableArray<ImmutableArray<string>> Tokens { get; } = tokens.Select(x => x.ToImmutableArray()).ToImmutableArray();
    }

    In which case there is no type relationship, even though structurally speaking the parameter and property types are equivalent.

  19. terrajobst commented on Aug 8, 2024

    @terrajobst
    Contributor

    for example one might reasonably expect that this is a valid model:

    That's fair, but I think this would violate our stated goal because it can't be roundtripped (and as far as I can tell nobody is asking for that yet).

    I suspect our solution probably needs to support more than Type.IsAssignableFrom, specifically handle conversion operators.

  20. eiriktsarpalis commented on Aug 8, 2024

    @eiriktsarpalis
    Member

    That's fair, but I think this would violate our stated goal because it can't be roundtripped

    Why not? The shapes of the two types are equivalent.

    (and as far as I can tell nobody is asking for that yet).

    We've had a few duplicates historically asking for variations of the same thing. I'm not saying we should actually build this, the point is we should have an "I know what I'm doing" mode that disables matching altogether.

    suspect our solution probably needs to support more than Type.IsAssignableFrom, specifically handle conversion operators.

    I think that's fair, although it will be tricky to implement full parity with language semantics using reflection.

  21. terrajobst commented on Aug 8, 2024

    @terrajobst
    Contributor

    I'm not saying we should actually build this, the point is we should have an "I know what I'm doing" mode that disables matching altogether.

    I think I'm missing how this would work? It seems if the values the constructor accepts can't be derived in an automatic fashion from the properties, then round tripping will fail. Having an expert mode wouldn't change that, right?

  22. eiriktsarpalis commented on Aug 8, 2024

    @eiriktsarpalis
    Member

    That's correct, however oftentimes this might be desirable (e.g. because the type is binding model so we only care about deserialization). At the same time, parameter matching itself doesn't offer any strong guarantees wrt round tripping properties, there are many reasons why it might still fail for a particular model (abstract types, non-public constructors).

  23. LeszekKalibrate commented on Sep 10, 2024

    @LeszekKalibrate

    4 years later and still simple deserialization, assign value for nullable param in ctor when there is non nullable field/property is not working.

  24. NullQubits commented on Oct 5, 2024

    @NullQubits

    4 years later and still simple deserialization, assign value for nullable param in ctor when there is non nullable field/property is not working.

    Not only that, this is also not working, which is extremely surprising to me

    public class Book
    {
        public IReadOnlyList<string> Pages { get; }
    
        public Book(IEnumerable<string> pages)
        {
            Pages = pages.ToList().AsReadOnly();
        }
    }
    
  25. barjonas commented on Apr 3, 2025

    @barjonas

    Without JsonContructor, there's no clean way to stop the constructor from (rightly) complaining that some properties might still be null. With it, for now, there's no way to tolerate incomplete data. What if someone changed the locks while you were on your round trip?

    Consider this class:

    [method: JsonConstructor]
    public class Animal(string? name, int? legCount, bool? hasLegs, Subphyla? subphyla, ImmutableArray<double>? toothSizes)
    {
        public Animal(string name) : this(name, null, null, null, null) {}
        public string Name { get; set; } = 
            name ?? throw new Exception("All animals must have a name");
        public bool HasLegs { get; set; } = 
            hasLegs ?? (!legCount.HasValue || legCount > 0); //Migrate legacy property legCount
        public Subphyla Subphyla { get; set; } = 
            subphyla.HasValue && Enum.IsDefined<Subphyla>(subphyla.Value) ? subphyla.Value : Subphyla.Mammal;
        public ImmutableArray<double> ToothSizes { get; set; } = 
            toothSizes ?? [];
    }

    I don't know of a more terse way to achieve all this:

    1. Define some values as optional, providing a default if missing.
    2. Define other values as mandatory, throwing a rich exception if missing.
    3. Stand up to null state analysis.
    4. Provide migration logic from serialized data from past versions.
    5. Avoid unnecessary assignments of default values just in case they're not set by the deserializer.

    It also supports inheritance and nesting very naturally and integrates well with logic to create new objects away from deserialization. I use this everywhere for settings, where version upgrades often mean new settings being introduced that will not be present in old data.

    By adding the JsonConstructor attribute, I'm declaring that I'm taking responsibility for declaring what inputs I'm expecting from the serial data and how they're going to map to my object. Nobody is adding that attribute by mistake or because it was the default template. I would expect the deserilaizer for a Type to look for a JsonConstructor first. If it finds one, why bother wasting cycles looking any further? What else would it need to know? What is the class of bug it's protecting me from? If all non-nullable parameters in the JsonConstructor are found in the serial data, round trip is done ✅ Pass nulls for nullable parameters that weren't matched and move let me deal with it! If I have a non-nullable parameter that is not found in the data then that's the time for an exception.

  26. KrzysztofBranicki commented on Jul 22, 2025

    @KrzysztofBranicki

    @eiriktsarpalis are there any plans to address this issue in the near future?

  27. eiriktsarpalis commented on Jul 22, 2025

    @eiriktsarpalis
    Member

    Not immediately, no. Sorry.

  28. michael-hawker commented on Apr 9, 2026

    @michael-hawker

    Yeah, running into this issue as well, as we want immutable properties to represent a fixed result of data in memory. However, we still want to serialize this to disk and later rehydrate the state later to re-process with a new pipeline (but we need to get the existing readonly data first still). But because our property is immutable, I can't deserialize it and do that conversion in the constructor from a similar non-immutable type as called out above.

    // custom constructor
    [JsonConstructor]
    public MyClass(Dictionary<string, IReadOnlyList<object?>> inputs) {}
    
    // Doesn't work
    public IReadOnlyDictionary<string, IReadOnlyList<object?>> Inputs { get; set; }
    
    // Works
    public Dictionary<string, IReadOnlyList<object?>> Inputs { get; set; }

    The current error message is super unhelpful as well:

    • It doesn't tell me which parameter of the constructor is an issue (and its type)
    • What json field/name/type is trying to be deserialized,
    • Or which thing doesn't match what...

    It just leaves me to guess and play whack-a-mole with removing parameters and guessing what's wrong... I just want to take the dictionary from the parameter of my constructor and make it read-only into my actual property... Though it does seem I can just align on the original IReadOnlyDictionary as a base, but that is not made clear as step for me to try by the current error message.

    It'd be really great to have more flexibility here and just let me own the construction of the object from whatever compatible types I can specify in the parameter list. It's weird too, as if I remove the offending parameters, I can construct a partial "invalid" object for the matching ones still, it won't complain. But if I add one that aligns to a property in my object and mismatches, now it does... This whole behavior is confusing. As @barjonas said above, by specifying this attribute we're taking responsibility for aligning the parameters coming in from deserialization to the proper translation/construction of the object. I also really like their example of using this with extra parameters to allow for schema updates with old property names, etc... too.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Team:Librariesapi-suggestionarea-System.Text.Jsonenhancement

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions