【发布时间】:2019-07-22 09:04:30
【问题描述】:
例如我有以下代码(C# - 控制台应用程序)
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;
}
输出是:
{"Name": "Test", "Code": { "Value": "CODE" }
我的期望是:
{"Name": "Test", "Code": "CODE" }
注意:AccountCode 是一个结构,但我想将其序列化/反序列化为普通字符串。我该怎么办?
【问题讨论】:
-
请不要在您的问题标题中放置标签,并请确保它能够描述您的问题。
-
可以实现自定义JsonConverter
-
无论如何使用这个结构有什么意义呢?与简单地使用字符串相比,它似乎没有任何好处......