如何在C#序列化类中动态替换PayPal Orders的paymentSource字段
解决PayPal Advanced Checkout订单请求的C#动态序列化问题
PayPal Advanced Checkout的v2订单请求中,payment_source下的键是动态的(比如前端传入的"paypal"或"card"),C#静态类无法直接对应这种动态结构,下面提供两种可行的实现方案:
方案1:使用Dictionary<string, object>直接定义动态结构
这种方式最简单直接,用字典承载payment_source的动态键值对:
定义请求模型类
using System.Collections.Generic; public class OrderRequest { public string intent { get; set; } public List<PurchaseUnit> purchase_units { get; set; } public Dictionary<string, object> payment_source { get; set; } } public class PurchaseUnit { public Amount amount { get; set; } } public class Amount { public string currency_code { get; set; } public string value { get; set; } }
控制器中构造并序列化请求
假设前端通过请求体传入paymentSource(字符串,如"paypal")和purchaseAmount:
using Newtonsoft.Json; [HttpPost] public IActionResult CreatePayPalOrder([FromBody] OrderRequestParams requestParams) { // 构造订单请求对象 var orderRequest = new OrderRequest { intent = "CAPTURE", purchase_units = new List<PurchaseUnit> { new PurchaseUnit { amount = new Amount { currency_code = "USD", value = requestParams.purchaseAmount } } }, payment_source = new Dictionary<string, object> { // 用前端传入的变量作为键,值可根据需求填充(这里是空对象) { requestParams.paymentSource, new {} } } }; // 序列化为符合PayPal要求的JSON string jsonRequest = JsonConvert.SerializeObject(orderRequest); // 后续调用PayPal API逻辑... return Ok(jsonRequest); } // 接收前端参数的模型 public class OrderRequestParams { public string paymentSource { get; set; } public string purchaseAmount { get; set; } }
方案2:使用JsonExtensionData特性(Newtonsoft.Json专属)
如果希望模型结构更清晰,可通过[JsonExtensionData]特性实现动态字段的序列化:
定义带扩展数据的模型类
using System.Collections.Generic; using Newtonsoft.Json; public class OrderRequest { public string intent { get; set; } public List<PurchaseUnit> purchase_units { get; set; } public PaymentSource payment_source { get; set; } } public class PurchaseUnit { public Amount amount { get; set; } } public class Amount { public string currency_code { get; set; } public string value { get; set; } } public class PaymentSource { // 这个字典会被序列化为对象的动态属性 [JsonExtensionData] private IDictionary<string, object> _additionalData; public PaymentSource(string paymentType) { _additionalData = new Dictionary<string, object> { { paymentType, new {} } }; } }
控制器中使用示例
[HttpPost] public IActionResult CreatePayPalOrder([FromBody] OrderRequestParams requestParams) { var orderRequest = new OrderRequest { intent = "CAPTURE", purchase_units = new List<PurchaseUnit> { new PurchaseUnit { amount = new Amount { currency_code = "USD", value = requestParams.purchaseAmount } } }, payment_source = new PaymentSource(requestParams.paymentSource) }; string jsonRequest = JsonConvert.SerializeObject(orderRequest); // 调用PayPal API逻辑... return Ok(jsonRequest); }
两种方案最终序列化后的JSON都会符合PayPal要求的结构,比如当paymentSource为"paypal"时,payment_source部分会生成:
"payment_source": { "paypal": {} }
内容的提问来源于stack exchange,提问作者lixid
相关产品推荐
相关产品推荐

