解析PayPal REST信用卡交易响应(JSON)

我通过C#ASP.NET 4.5框架网站使用最新版本的PayPal REST API进行PayPal和信用卡交易。 事务在沙箱中完美运行,响应显示与事务关联的所有数据。

我想要做的是使用标签以更友好的方式显示该信息。 如何将JSON响应解析为标签或文本框?

这是显示不友好响应的当前代码。

try { APIContext apiContext = Configuration.GetAPIContext(); Payment createdPayment = pymnt.Create(apiContext); CurrContext.Items.Add("ResponseJson", JObject.Parse(createdPayment.ConvertToJson()).ToString(Formatting.Indented)); } catch (PayPal.Exception.PayPalException ex) { if (ex.InnerException is PayPal.Exception.ConnectionException) { Label4.Text = (((PayPal.Exception.ConnectionException)ex.InnerException).Response); } else { Label4.Text = (ex.Message); } CurrContext.Items.Add("Error", ex.Message); } CurrContext.Items.Add("RequestJson", JObject.Parse(pymnt.ConvertToJson()).ToString(Formatting.Indented)); 

我今晚必须这样做,这有点工作。 以下是如何至少获取结构化对象以利用和编写自己的翻译类/方法。

 public class PaypalApiError { public string name { get; set; } public string message { get; set; } public List> details { get; set; } public string debug_id { get; set; } public string information_link { get; set; } } 

然后,您可以通过稍微修改代码来获取可用对象。

 catch (PayPal.Exception.PayPalException ex) { string error = ""; if (ex.InnerException is PayPal.Exception.ConnectionException) { var paypalError = JsonConvert.DeserializeObject(((PayPal.Exception.ConnectionException)ex.InnerException).Response); // method below would parse name/details and return a error message error = ParsePaypalError(paypalError); } else { error = ex.Message; } return new PaymentDataResult(){ Success = false, Message = error }; } 

您必须创建ParsePaypalError()方法,以根据对您重要的内容返回错误。 我没有看到一种简单的方法来解析它,只是当它是最常见的状态’VALIDATION_ERROR’时,只显示有用的消息。 这是错误状态/消息的链接。

PayPal Rest API错误