簡體   English   中英

Newtonsoft JSON 重命名屬性名稱取決於另一個屬性

[英]Newtonsoft JSON rename the property name depends on another property

我有一個帶有以下字段的 class。

public class Payment
{
    public string type { get; set; }
    public string issuer { get; set; }
    public string identifier { get; set; }
    public float price { get; set; }
}

“類型”字段可以是“禮品卡”或“信用卡”。
我想序列化它取決於“類型”字段。

{
   "type": "Giftcard",
   "giftcard_no": "111111111111",
   "giftcard_price": 100
}
{
   "type": "Creditcard",
   "issuer": "AMEX",
   "last_4_digits": "1000",
   "creditcard_price": 100
}

如您所見,字段名稱因“類型”字段而異。
如果是 Giftcard,“發行人”字段將被忽略。

我發現了類似的問題,但找不到正確的答案。
我將不勝感激任何幫助。

謝謝你。

在我看來,您想要的是不同的子類,使用type來確定在反序列化時使用哪一個。 我發現JsonSubTypes package ( GitHub repo ) 對此非常有效。

你會有這樣的事情:

[JsonConverter(typeof(JsonSubtypes), "type")]
[JsonSubtypes.KnownSubType(typeof(GiftCard), "Giftcard")]
[JsonSubtypes.KnownSubType(typeof(CreditCard), "Creditcard")]
public class Payment
{
    [JsonProperty("type")]
    public virtual string Type { get; }
}

public class CreditCard : Payment
{
    public override string Type => "Creditcard";

    [JsonProperty("issuer")
    public string Issuer { get; set; }

    // Etc, other properties
}

public class GiftCard : Payment
{
    public override string Type => "Giftcard";

    [JsonProperty("giftcard_no")]
    public string GiftCardNumber { get; set; }

    // Etc, other properties
}

有多種不同的選項可以准確地說明您如何注冊事物 - GitHub 存儲庫上的 README 提供了具體示例,這非常有用。

然后反序列化為Payment ,但返回值將是對GiftCardCreditCard實例的引用。

暫無
暫無

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

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