构建NowPayments支付API遇JSON解析错误,求解决方法
解决NowPayments API JSON解析错误的思路
问题根源
你手动拼接JSON字符串的方式极易引发格式错误:
- 原代码中
price_amount行末尾缺少逗号,直接破坏了JSON的结构,导致API无法正确解析请求,返回的不是有效JSON格式内容,最终触发解析报错。 - 如果文本框输入的
priceAmount包含非数字字符(比如字母、符号),会让price_amount的值不符合API要求的数字类型,同样会导致API返回错误内容而非预期JSON,进而解析失败。
解决步骤
1. 用对象序列化替代手动拼接JSON(最推荐)
手动拼接JSON容错率极低,直接用C#类定义请求结构,再序列化生成标准JSON,能彻底规避格式问题:
首先定义请求模型类:
public class InvoiceRequest { public decimal PriceAmount { get; set; } public string PriceCurrency { get; set; } public string OrderId { get; set; } public string OrderDescription { get; set; } public string IpnCallbackUrl { get; set; } public string SuccessUrl { get; set; } public string CancelUrl { get; set; } }
然后修改请求代码:
// 先验证输入是否为有效数字 if (!decimal.TryParse(txtBoxTopUpBalance.Text, out decimal priceAmount)) { // 提示用户输入合法金额,比如弹窗提示 return; } var client = new RestClient("https://api.nowpayments.io/v1/invoice"); client.Timeout = -1; var request1 = new RestRequest(Method.POST); request1.AddHeader("x-api-key", apiKey); request1.AddHeader("Content-Type", "application/json"); // 实例化请求对象 var invoiceRequest = new InvoiceRequest { PriceAmount = priceAmount, PriceCurrency = "usd", OrderId = "RGDBP-21314", OrderDescription = "order #1", IpnCallbackUrl = "https://nowpayments.io", SuccessUrl = "https://nowpayments.io", CancelUrl = "https://nowpayments.io" }; // 序列化为标准JSON var body = JsonConvert.SerializeObject(invoiceRequest, Formatting.Indented); request1.AddParameter("application/json", body, ParameterType.RequestBody); IRestResponse response1 = client.Execute(request1); // 先检查响应是否成功,再解析 if (response1.IsSuccessful) { JObject responseObject = JObject.Parse(response1.Content); invoiceUrl = responseObject["invoice_url"].ToString(); } else { // 处理请求失败的情况,比如打印错误信息 Console.WriteLine($"请求失败:{response1.ErrorMessage}"); }
2. 必须手动拼接的临时修复(不推荐)
如果暂时不想用序列化,至少要修正JSON格式错误:
- 在
priceAmount后面加上逗号:@" ""price_amount"":" + priceAmount + "," + "\n" - 强制验证
priceAmount是纯数字,比如用decimal.TryParse检查,避免非法字符混入
额外建议
- 永远不要手动拼接JSON,序列化是行业标准做法,能避免99%的格式问题。
- 发送请求前一定要验证用户输入的合法性,确保金额是有效数字,避免无效请求。
内容的提问来源于stack exchange,提问作者vdmua
相关产品推荐
相关产品推荐

