自定义JSON序列化程序

时间:2016-06-16 18:26:09

标签: c# json json.net jsonserializer

我有一个班级,

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。可能我应该使用自定义序列化器?有没有办法使用同一个类实现这一目标。

1 个答案:

答案 0 :(得分:0)

您可以使用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;
    }
}

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

相关问题