【问题标题】:C# - Json converter [duplicate]C# - Json 转换器
【发布时间】: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
  • 无论如何使用这个结构有什么意义呢?与简单地使用字符串相比,它似乎没有任何好处......

标签: c# json


【解决方案1】:

Account 类中的代码是 AccountCode 的一个对象,这就是为什么在序列化它时,JsonConverter 将它放入花括号中。您必须将 Code 属性更改为字符串或操作序列化的 json

【讨论】:

    猜你喜欢
    • 2018-12-13
    • 1970-01-01
    • 2012-10-15
    • 1970-01-01
    • 2013-10-24
    • 2017-11-28
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多