How to Deserialize a type with a Parameterized Constructor using JIL?

1.9k Views Asked by At

I have a simple immutable POCO defined as:

public sealed class Person
{
    public Person(string name)
    {
        Name = name;
        TimeStamp = DateTimeOffset.UtcNow;
    }

    public DateTimeOffset TimeStamp { get; }    
    public string Name { get; }
}

I then do a simple ser-deserialization:

var p = new Person("Mr Right").Dump();

var ser = JSON.Serialize(p).Dump();

// Throws Deserialization Exception, Error occured building a deserializer, 
// Expected a parameterless constructor...
JSON.Deserialize<Person>(ser).Dump();

The serialization is successful producing:

{"TimeStamp":"/Date(1456412550349+0000)/","Name":"Mr Right"}

But the deserialization throws, any idea how to fix it? Does JIL support deserialization of types with Parameterized Constructors?

1

There are 1 best solutions below

0
On BEST ANSWER

As you note, Jil does not support deserializing types without parameterless constructors*. This is because there's no perfectly reliable way to map parameters to a constructor to public members (fields and properties).

When Jil deserializes it creates an empty object of the given type, then sets each member it encounters in the JSON stream. Creating an empty object isn't possible without a default constructor.

*There are two exceptions to this, anonymous types and primitive wrapper types. Anonymous types have a language-defined mapping between parameters and members, and primitive wrapper types are single-parameter (and opt-in) - both cases are resolvable, while the general case isn't.