Skip to content

JsonConstrutor different behavior between Newtonsoft.Json and System.Text.Json #46480

Closed

Description

@NN---

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

Activity

  1. added
    untriaged
    on Dec 31, 2020
  2. Clockwork-Muse commented on Dec 31, 2020

    @Clockwork-Muse
    Contributor

    Um, if you throw an exception like that, why not just make the constructor take a non-nullable?

  3. NN--- commented on Dec 31, 2020

    @NN---
    ContributorAuthor

    It is a general question.
    The argument validation can be more complicated than this.

  4. layomia commented on Jan 25, 2021

    @layomia
    Contributor

    Dup of #44428.

  5. removed
    untriaged
    on Jan 25, 2021
  6. ghost locked as resolved and limited conversation to collaborators on Feb 24, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions