Newtonsoft JSON重命名属性名称取决于另一个属性

Shi J

我有一个包含以下字段的课程。

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软件包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您需要反序列化到,但是返回值将是对GiftCard实例的引用CreditCard

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章