Skip to content

JsonSerializer support for immutable classes and structs. #29895

Closed

Description

@johanneshoehn

A common pattern is to make data objects immutable for many different reasons.
For example Point:

public class Point
{
    int X { get; }

    int Y { get; }

    public Point(int x, int y) => (X, Y) = (x, y);

    public void Deconstruct(out int x, out int y) => (x, y) = (X, Y);
}

It would be very helpful if JsonSerializer supported immutable classes/structs like that, especially since Newtonsoft Json.NET supports deserialization through the constructor.

However there are a few issues surrounding immutable types:

  • Constructor parameter names are usually camelCase while Properties are PascalCase. One way to solve this is by setting JsonSerializerOptions.PropertyNameCaseInsensitive in to true. Another way is to use the Deconstruct-pattern introduced in C# 7.0, instead of Properties for serialization.

  • There may be several constructors (and Deconstruct methods). So it's not always clear which to use. Newtonsoft Json.NET uses a JsonConstructorAttribute.htm, which has the disadvantage that the data objects need to know about serialization.

  • Constructor parameters, properties and Deconstruct method parameters might not match up, possibly leading to confusing situations where deserializing a previously serialized object does not work.

  • Immutable structs always still have a default parameterless constructor.

Activity

  1. changed the title [-]`JsonSerializer` support for immutable `class`es and `struct`s.[/-] [+]JsonSerializer support for immutable classes and structs.[/+] on Jun 15, 2019
  2. ahsonkhan commented on Jun 18, 2019

    @ahsonkhan
    Contributor

    This is a known limitation of the System.Text.Json serializer for v1. We plan to support this in the future.

  3. steveharter commented on Jun 18, 2019

    @steveharter
    Contributor

    You can write a custom converter for this.

  4. Gnbrkm41 commented on Jun 19, 2019

    @Gnbrkm41
    Contributor

    I totally was going to write an issue about this, glad I noticed this before that 🙃

    I personally thought that writing a private setter on otherwise a readonly property purely because of JSON (de)serialization is kind of hacky. I know that I could write a custom converter (when it's implemented) or use a constructor (which I remember will be supported soon? I could be wrong) but... that's effort ☺️

  5. steveharter commented on Jun 19, 2019

    @steveharter
    Contributor

    For the 3.0 release, there is no planned additional support for calling a non-default constructor during deserialization. That would have to be done by a custom converter.

  6. Gnbrkm41 commented on Jun 19, 2019

    @Gnbrkm41
    Contributor

    That's fine, as long as it's in the plan in some way... One step at a time 😁

  7. khellang commented on Oct 22, 2019

    @khellang
    Member
  8. Gnbrkm41 commented on Oct 22, 2019

    @Gnbrkm41
    Contributor

    @khellang, it probably overlaps because this issue is dotnet/corefx#38569 😄 I guess you meant 41973?

  9. khellang commented on Oct 22, 2019

    @khellang
    Member
  10. Mike-E-angelo commented on Oct 22, 2019

    @Mike-E-angelo

    3dzwv6
    😅

  11. danstur commented on Nov 15, 2019

    @danstur

    @ahsonkhan Is there work currently being done on this issue? If not, is this something where a pull request would be considered?

  12. git-net commented on Nov 23, 2019

    @git-net

    seems would support Deserialize anonymous object?

  13. layomia commented on Nov 25, 2019

    @layomia
    Contributor

    From @endeffects in dotnet/corefx#40399:

    Please provide support for custom constructors and allow to specify the constructor with an attribute.

  14. ahsonkhan commented on Nov 25, 2019

    @ahsonkhan
    Contributor

    From @EdiWang in https://github.com/dotnet/corefx/issues/41102:

    The following code throws exception.

    static void Main(string[] args)
    {
        var obj = new Response(true, "Hi") { ResponseCode = 100 };
        var json = System.Text.Json.JsonSerializer.Serialize(obj);
    
        // System.NotSupportedException: 'Deserialization of reference types without parameterless constructor is not supported.
        var response = System.Text.Json.JsonSerializer.Deserialize<Response>(json);
    
        Console.WriteLine(response.Message);
    }
    
    public class Response
    {
        public bool IsSuccess { get; set; }
    
        public string Message { get; set; }
    
        public int ResponseCode { get; set; }
    
        public Response(bool isSuccess = false, string message = "")
        {
            IsSuccess = isSuccess;
            Message = message;
        }
    }

    Response class is considered not having a parameterless constructor, but actually it does use default values for parameters, that can be used just like a parameterless constructor, like this:

    var test = new Response();

    Could the new JSON API check if the constructor parameters have default values before consider it not paremeterless?

    Related Issues:
    #29490

    PR:
    dotnet/corefx#38061

  15. manne commented on Jan 15, 2020

    @manne
    Contributor

    I have started to implement a custom converter for immutable types here https://github.com/manne/obviously/tree/master/src/system.text.json.

    The converter is able to read "basic" types. The type must have exactly one constructor with at least one parameter. The type has not be sealed.

    Example

    public sealed class ProgramSettings
    {
        public ProgramSettings(Uri baseUrl, string adminName, string adminPassword)
        {
            BaseUrl = baseUrl;
            AdminName = adminName;
            AdminPassword = adminPassword;
        }
    
        public Uri BaseUrl { get; }
        public string AdminName { get; }
        public string AdminPassword { get; }
    }
    
    public void DeserializeSettings()
    {
        const string settingsJson = @"{""BaseUrl"": ""https://example.com:8999"", ""AdminName"": ""admin"", ""AdminPassword"": ""topsecret""}";
        var options = new JsonSerializerOptions();
        options.Converters.Add(new ImmutableConverter());
    
        var programSettings = JsonSerializer.Deserialize<ProgramSettings>(settingsJson, options);
        var baseUrl = programSettings.BaseUrl; // https://example.com:8999
        var adminName = programSettings.AdminName; // admin
        var adminPassword = programSettings.AdminPassword; // topsecret
    }

    I have uploaded a nuget package Obviously.System.Text.Json, it is not yet indexed.

    Feedback and PRs are always welcome 😉

  16. ahsonkhan commented on Jan 25, 2020

    @ahsonkhan
    Contributor

    From @ahedreville in #1925:

    I missed the Newtonsoft.Json the nice attribute JsonConstructor that is very handy when serializing classes that do not expose public constructor.. like the one below...

        public class Envelope<T>
        {
            public T Result { get; }
            public string ErrorMessage { get; }
            public DateTime TimeGenerated { get; }
    
            [JsonConstructor]                                             // This constructor is marked as the valid JsonConvert constructor for JsonConvert.DeserializeObject usage.
            protected internal Envelope(T result, string errorMessage)
            {
                Result = result;
                ErrorMessage = errorMessage;
                TimeGenerated = DateTime.UtcNow;
            }
        }
    
        public sealed class Envelope : Envelope<string>
        {
            private Envelope(string error)
            : base(null, error)
            {
            }
    
            public static Envelope Ok() => new Envelope(null);
            public static Envelope<T> Ok<T>(T result) => new Envelope<T>(result, default);
    
            public static Envelope Error(string error) => new Envelope(error);
            public static Envelope<T> Error<T>(T result) => new Envelope<T>(result, default);
            public static Envelope<T> Error<T>(T result, string error) => new Envelope<T>(result, error);
        }
    
  17. transferred this issue fromdotnet/corefxon Feb 1, 2020
  18. added this to the 5.0 milestone on Feb 1, 2020
  19. ghost locked as resolved and limited conversation to collaborators on Dec 12, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-System.Text.Jsonjson-functionality-doc

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions