Repository navigation
Description
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
layomia commentedon Nov 12, 2020
Why make the constructor parameter nullable? The
AGuidproperty is non-nullable which means thatnullwill never be serialized. Are you expectingnullJSON tokens to bind with the parameter on deserialization? Where would this JSON come from?JSkimming commentedon Nov 13, 2020
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.
layomia commentedon Jan 25, 2021
From @https://github.com/NN--- in #46480:
layomia commentedon Jan 25, 2021
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.
GabeDeBacker commentedon Jan 25, 2021
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.
JSkimming commentedon Jan 25, 2021
@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 are also blocked. Our workaround is to stick with Newtonsoft.Json.
layomia commentedon Jan 25, 2021
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.
69 remaining items
eiriktsarpalis commentedon Aug 7, 2024
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
raffaeler commentedon Aug 7, 2024
@eiriktsarpalis This was indeed the initial proposal:
Please ensure to add a global option in the
JsonSerializerOptions(the proposed property wasConstructorUseRelaxedPropertyMatching) so that we can use it without attribute decoration.Please also consider this comment.
terrajobst commentedon Aug 7, 2024
@eiriktsarpalis
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 isT[]orImmutableArray<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.
eiriktsarpalis commentedon Aug 8, 2024
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:
In which case there is no type relationship, even though structurally speaking the parameter and property types are equivalent.
terrajobst commentedon Aug 8, 2024
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.eiriktsarpalis commentedon Aug 8, 2024
Why not? The shapes of the two types are equivalent.
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.
I think that's fair, although it will be tricky to implement full parity with language semantics using reflection.
terrajobst commentedon Aug 8, 2024
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?
eiriktsarpalis commentedon Aug 8, 2024
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).
WIP: Start implementing sync endpoint with all its many types. Curren…
LeszekKalibrate commentedon Sep 10, 2024
4 years later and still simple deserialization, assign value for nullable param in ctor when there is non nullable field/property is not working.
NullQubits commentedon Oct 5, 2024
Not only that, this is also not working, which is extremely surprising to me
barjonas commentedon Apr 3, 2025
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:
I don't know of a more terse way to achieve all this:
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
JsonConstructorattribute, 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 aTypeto look for aJsonConstructorfirst. 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 theJsonConstructorare 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.KrzysztofBranicki commentedon Jul 22, 2025
@eiriktsarpalis are there any plans to address this issue in the near future?
eiriktsarpalis commentedon Jul 22, 2025
Not immediately, no. Sorry.
michael-hawker commentedon Apr 9, 2026
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.
The current error message is super unhelpful as well:
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
IReadOnlyDictionaryas 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.