Nino supports custom constructors to perform additional operations during deserialization (e.g., initializing non-serialized fields). Use the [NinoConstructor] attribute to specify which members should be passed as arguments to the constructor.
Behavior by Type:
- Records: Nino prioritizes the primary constructor. Use
[NinoConstructor] to override this. - Classes: Nino automatically uses the first public constructor if it is parameterless or if all parameters match the names of fields/properties being deserialized. Use
[NinoConstructor] to specify a different one. - Structs: Nino automatically uses the parameterless constructor. Use
[NinoConstructor] to force a parameterized constructor.
Restrictions:
- The constructor must be
public. - The number of parameters in the constructor must match the number of parameters listed in the
[NinoConstructor] attribute. - Parameters in the attribute must match the names (case-insensitive) of fields or properties that are actually being serialized.
[NinoType]
public record SimpleRecord
{
public int Id;
public string Name;
public DateTime CreateTime;
// This constructor will be used for deserialization
[NinoConstructor(nameof(Id), nameof(Name))]
public SimpleRecord(int id, string name)
{
Id = id;
Name = name;
CreateTime = DateTime.Now; // Initialize non-serialized or derived field
}
}
[NinoType]
public struct SimpleStruct
{
public int Id;
public string Name;
public DateTime CreateTime;
// Force struct to use this instead of parameterless constructor
[NinoConstructor(nameof(Id), nameof(Name), nameof(CreateTime))]
public SimpleStruct(int a, string b, DateTime c)
{
Id = a;
Name = b;
CreateTime = c;
}
}