How do I add an attribute to a record's primary constructor?

Viewed 233

I have a record with an additional convenience constructor:

public record PublishedTestMethod(Guid Id, string Name, int Version, string Status, Guid? Publisher,
    DateTimeOffset? DatePublished)
{
    public PublishedTestMethod(TestMethod tm) : this(tm.Id, tm.Name, tm.Version, tm.Status, tm.Publisher,
        tm.DatePublished)
    {
    }
}

I would like to deserialize this from a JSON object:

JsonConvert.DeserializeObject<PublishedTestMethod>(json);

I get the error:

Unable to find a constructor to use for type Namespace.PublishedTestMethod. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute.

Ideally, I'd like to assign the [JsonConstructor] attribute to the long constructor, as I think this would let it map nicely from the JSON. Adding it to the record itself doesn't work, and I can't see an attribute target for a constructor. Is there a way to do this?

1 Answers

I am not sure, what you want is syntactically possible.

What I would have done is something like this:

public static class TestMethodExtensions
{
    public static PublishedTestMethod ToRecord( this TestMethod tm )
    {
        PublishedTestMethod myRecord = new ( tm.Id, 
                                        tm.Name, 
                                        tm.Version, 
                                        tm.Status, 
                                        tm.Publisher,
                                        tm.DatePublished);
         return myRecord;
    }
}

So, you can just do

PublishedTestMethod ptm = myTestMethodInstance.ToRecord();
Related