[英]Newtonsoft change JSON property name dynamically with enum
如何使用Newtonsoft JSON.net更改屬性名稱,我需要JSON如下所示。 PaymentMethod具有一個內部屬性,該屬性會更改enum PaymentMethodEnum {Cash, Card, Debit, Check }
Cash case
"PaymentMethod": {
"Cash": { }
}
Card case
"PaymentMethod": {
"Card" : {
"Authorization": "####",
"Bin": "####",
"Reference": "00#####"
}
}
Debit case
"PaymentMethod": {
"Debit": {
"DocumentType": "DNI",
"DocumentNumber": "##########3",
"Account": "xxxx-####"
}
}
Check case
"PaymentMethod": {
"Check": {
"BankCode": "MMMmmm",
"Number": "xxxx-xxxx-####",
"Account": "###########"
}
}
這是我的課
public class ChargeRq
{
[Required]
[JsonProperty(PropertyName = "DistributorId")]
public int DistributorId { get; set; }
[Required]
[JsonProperty(PropertyName = "AgentId")]
public int AgentId { get; set; }
[Required]
[JsonProperty(PropertyName = "Reference")]
public string Reference { get; set; }
[JsonProperty(PropertyName = "Invoices")]
public IEnumerable<Invoice> Invoices { get; set; }
[Required]
[JsonProperty(PropertyName = "Total")]
public int Total { get; set; }
[Required]
[JsonProperty(PropertyName = "PaymentMethod")]
public Payment PaymentMethod { get; set; }
}
// --------------------
public class Payment
{
// ???
}
// -------------------
public class Card
{
[Required]
[JsonProperty(PropertyName = "Authorization")]
public string Authorization { get; set; }
[Required]
[JsonProperty(PropertyName = "Bin")]
public string Bin { get; set; }
[Required]
[JsonProperty(PropertyName ="Reference")]
public string Reference { get; set; }
}
public class Cash { }
public class Debit
{
[Required]
[JsonProperty(PropertyName = "DocumentType")]
public string DocumentType { get; set; }
[Required]
[JsonProperty(PropertyName = "DocumentNumber")]
public string DocumentNumber { get; set; }
[Required]
[JsonProperty(PropertyName = "Account")]
public string Account { get; set; }
}
public class Check
{
[Required]
[JsonProperty(PropertyName = "BankCode")]
public string BankCode { get; set; }
[Required]
[JsonProperty(PropertyName = "Number")]
public string Number { get; set; }
[Required]
[JsonProperty(PropertyName = "Account")]
public string Account { get; set; }
}
因此,當我從第三方服務獲得此JSON時,我需要驗證JSON格式是否包含ChargeRq的付款方式。 我們這樣服務
public HttpResponseMessage TestRequestFormatData([FromBody]ChargeRq request) { }
我建議為每個PaymentMethod使用一個屬性
public class Payment
{
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public Card Card { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public Debit Debit { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public Check Check { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public Cash Cash { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.