简体   繁体   English

自定义JSON序列化器

[英]Custom JSON serializer

I have a class, 我有课

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; }
}

when I serialize this, the customerId is not there. 当我将此序列化时,customerId不存在。 And that's how I wanted it to work. 这就是我希望它起作用的方式。 I have a separate method where I need to send the customerId back. 我有一个单独的方法,我需要将customerId发送回去。 so may be I should use a custom serializer? 所以我应该使用自定义序列化程序吗? is there a way to achieve this using the same class. 有没有一种方法可以使用相同的类来实现。

You can use the conditional serialization feature of JSON.Net: 您可以使用JSON.Net的条件序列化功能:

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;
    }
}

Now Json.Net will only serialize CustomerId if you set IncludeCustomerId to true . 现在,如果将IncludeCustomerId设置为true则Json.Net将仅序列化CustomerId

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM