如何解决Newtonsoft JSON重命名属性名称取决于另一个属性
我有一个包含以下字段的课程。
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
,但是返回的值将是对GiftCard
或CreditCard
实例的引用。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。