如何使用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) { }
答案 0 :(得分:0)
我建议为每个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; }
}