I just had to do something similar yesterday. Although in my case I only needed to change property name mappings, you can change types with JsonConverter
like so:
public enum UserStatus
{
NotConfirmed,
Active,
Deleted
}
public class User
{
public string UserName { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public UserStatus Status { get; set; }
}
According to the reference:
JsonConverterAttribute
The JsonConverterAttribute specifies which JsonConverter is used to convert an object.
The attribute can be placed on a class or a member. When placed on a class, the JsonConverter specified by the attribute will be the default way of serializing that class. When the attribute is on a field or property, then the specified JsonConverter will always be used to serialize that value.
The priority of which JsonConverter is used is member attribute, then class attribute, and finally any converters passed to the JsonSerializer.
According to the class reference, the type is of System.Type.
It doesn't sound needed, but possibly also of interest may be the JsonConstructorAttribute
:
The JsonConstructorAttribute instructs the JsonSerializer to use a specific constructor when deserializing a class. It can be used to create a class using a parameterized constructor instead of the default constructor, or to pick which specific parameterized constructor to use if there are multiple:
public class User
{
public string UserName { get; private set; }
public bool Enabled { get; private set; }
public User()
{
}
[JsonConstructor]
public User(string userName, bool enabled)
{
UserName = userName;
Enabled = enabled;
}
}