编辑 - 已解决: 发布的结果是我们的日志代码和json.org如何处理Javascript null和Javascript undefined之间的区别的组合。我们的日志记录代码没有在对象中打印空值,所以虽然我看到的json对象没有“invoice”字段,但实际输入的字段为空“invoice”字段。 JSONObject的.has()方法报告有一个“invoice”字段,但是当我尝试访问它时,它的值为null,因此无法访问它。用.isNull()检查(考虑缺少字段和空值)替换.has()检查解决了问题。
在我的Google App Engine应用程序中,我们以json的形式解析webhook数据,并根据json对象中某个键的存在关闭不同的代码路径 - 如果$ .data.object.invoice存在,我们会做一些工作,否则我们没有。但是,在生产中运行时,这种检测似乎被打破了。我做了一个简单的
jsonObject.getJSONObject("data").getJSONObject("object").has("invoice")
检查发票密钥,有时即使发票密钥不存在,也会返回true。我遇到了这个错误,因为我们确实在它存在时使用了发票值,并且我正在尝试访问JSONExceptions,即使它受到has()检查的保护。我添加了以下日志记录,以确保我正在做的一切正确:
boolean isAutomaticCharge = jsonObject.getJSONObject("data").getJSONObject("object").has("invoice");
boolean doesGettingStringWork;
try {
jsonObject.getJSONObject("data").getJSONObject("object").getString("invoice");
doesGettingStringWork = true;
}
catch (JSONException e) {
doesGettingStringWork = false;
}
Logger.log("The value of automatic charge is: " + isAutomaticCharge);
Logger.log("Geting the invoice worked? " + doesGettingStringWork);
Logger.log(jsonObject.getJSONObject("data").getJSONObject("object").toString());
if (isAutomaticCharge) {
handleFailedCharge(jsonObject);
}
else {
//Manual Charge
}
在生产中,以下数据导致isAutomaticCharge为true且doesGettingStringWork为false:
{
"id": "evt_16vC0s1WJGsEk3Qvnstmq6fa",
"object": "event",
"api_version": "2014-03-28",
"created": 1444678274,
"data": {
"object": {
"id": "ch_16vC0r1WJGsEk3Qv5rxezNQj",
"object": "charge",
"amount": 1900,
"amount_refunded": 0,
"captured": false,
"card": {
"id": "card_16vC0k1WJGsEk3Qvl9LLEt5K",
"object": "card",
"brand": "MasterCard",
"country": "CA",
"customer": "cus_79V0ZH6qFFA4K0",
"cvc_check": "fail",
"exp_month": 9,
"exp_year": 2016,
"fingerprint": "ifxs23sixYzpKant",
"funding": "credit",
"last4": "6912",
"metadata": {},
"name": "derek@footbole.com",
"type": "MasterCard"
},
"created": 1444678273,
"currency": "usd",
"customer": "cus_79V0ZH6qFFA4K0",
"failure_code": "card_declined",
"failure_message": "Your card was declined.",
"fraud_details": {},
"livemode": true,
"metadata": {},
"paid": false,
"refunded": false,
"refunds": [],
"source": {
"id": "card_16vC0k1WJGsEk3Qvl9LLEt5K",
"object": "card",
"brand": "MasterCard",
"country": "CA",
"customer": "cus_79V0ZH6qFFA4K0",
"cvc_check": "fail",
"exp_month": 9,
"exp_year": 2016,
"fingerprint": "ifxs23sixYzpKant",
"funding": "credit",
"last4": "6912",
"metadata": {},
"name": "derek@footbole.com",
"type": "MasterCard"
},
"status": "failed"
}
},
"livemode": true,
"pending_webhooks": 2,
"request": "req_79V0v7433eb9hZ",
"type": "charge.failed"
}
当我在本地运行代码并将其提供给json时,它按预期工作,isAutomaticCharge和doesGettingStringWork都是假的。
我正在运行org.json的版本20140107。我为每个请求声明了一个新的JSONObject,因此线程不应成为问题。有没有其他人在Google App Engine上运行org.json时遇到问题?