【问题标题】:Custom JSON serializer自定义 JSON 序列化器
【发布时间】:2016-06-16 18:26:08
【问题描述】:

我有课,

partial class Customer
{
    [JsonProperty]
    public string Name { get; set; }

    [JsonProperty]
    public string Address{ get; set; }

    [JsonProperty]
    public string CardInfo { get; set; }         

    public int CustomerId { get; set; }
}

当我序列化它时,customerId 不存在。这就是我希望它工作的方式。 我有一个单独的方法,我需要将 customerId 发回。那么我应该使用自定义序列化程序吗?有没有办法使用同一个类来实现这一点。

【问题讨论】:

  • 序列化 Customer 类的代码是什么样的?
  • 如果您需要对多种类型的多个属性执行此操作,您可以考虑使用来自Conditional member serialization based on query parameter? 的答案。
  • @Jeff 我只是在内置转换器中使用 json.net。 JsonConvert.SerializeObject(客户)

标签: c# json json.net jsonserializer


【解决方案1】:

您可以使用 JSON.Net 的conditional serialization 功能:

partial class Customer
{
    // Ignoring the property since it's only used to indicate if we should serialize
    // CustomerId or not
    [JsonIgnore]
    public bool IncludeCustomerId {get;set;}

    [JsonProperty]
    public string Name { get; set; }

    [JsonProperty]
    public string Address{ get; set; }

    [JsonProperty]
    public string CardInfo { get; set; }         

    public int CustomerId { get; set; }

    public bool ShouldSerializeCustomerId()
    {
        return IncludeCustomerId;
    }
}

现在 Json.Net 将仅在您将 IncludeCustomerId 设置为 true 时序列化 CustomerId

【讨论】:

    猜你喜欢
    • 2011-04-12
    • 1970-01-01
    • 2011-02-25
    • 2015-02-17
    • 2018-05-06
    • 2016-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多