簡體   English   中英

自定義JSON序列化器

[英]Custom JSON serializer

我有課

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發送回去。 所以我應該使用自定義序列化程序嗎? 有沒有一種方法可以使用相同的類來實現。

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

現在,如果將IncludeCustomerId設置為true則Json.Net將僅序列化CustomerId

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM