Example I have following code (C# - Console App)
static async Task MainAsync(string[] args)
{
Account account = new Account { Name = "Test", Code = (AccountCode)"Code" };
Console.WriteLine(JsonConvert.SerializeObject(account));
}
public class Account
{
public string Name { get; set; }
public AccountCode Code { get; set; }
}
public struct AccountCode
{
public AccountCode(string value)
: this()
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException("AccountCode cannot be null or empty.");
}
Value = value.ToUpperInvariant();
}
public string Value { get; set; }
public static explicit operator AccountCode(string value)
{
return new AccountCode(value);
}
public static explicit operator AccountCode? (string value)
{
if (string.IsNullOrEmpty(value))
{
return null;
}
else
{
return new AccountCode(value);
}
}
public static explicit operator string(AccountCode code)
{
return code.Value;
}
public override bool Equals(object obj)
{
return obj is AccountCode && this == (AccountCode)obj;
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
public static bool operator ==(AccountCode x, AccountCode y)
{
return string.Equals(x.Value, y.Value, StringComparison.InvariantCultureIgnoreCase);
}
public static bool operator !=(AccountCode x, AccountCode y)
{
return !string.Equals(x.Value, y.Value, StringComparison.InvariantCultureIgnoreCase);
}
public override string ToString()
{
return Value;
}
The output is:
{"Name": "Test", "Code": { "Value": "CODE" }
My expectation is:
{"Name": "Test", "Code": "CODE" }
Note: AccountCode is a struct but I would like to serialize/deserialize as a normal string. How should I do?