我有以下響應,並且我試圖提取sale
和related_resources
下的id
。從JSONObject響應中提取數據
到目前爲止,我已經嘗試檢索此ID與以下,但我想我試圖得到一個陣列的兩倍(原因是他們有一個[
盈他們會在錯誤的軌道。
confirm.toJSONObject().getJSONObject("response").getJSONArray("transactions").getJSONArray("related_resources")
的Eclipse然後會顯示以下信息The method getJSONArray(int) in the type JSONArray is not applicable for the arguments (String)
什麼是正確的方法來提取所需的數據
{
"id": "PAY-17S8410768582940NKEE66EQ",
"create_time": "2013-01-31T04:12:02Z",
"update_time": "2013-01-31T04:12:04Z",
"state": "approved",
"intent": "sale",
"payer": {
"payment_method": "credit_card",
"funding_instruments": [
{
"credit_card": {
"type": "visa",
"number": "xxxxxxxxxxxx0331",
"expire_month": "11",
"expire_year": "2018",
"first_name": "Betsy",
"last_name": "Buyer",
"billing_address": {
"line1": "111 First Street",
"city": "Saratoga",
"state": "CA",
"postal_code": "95070",
"country_code": "US"
}
}
}
]
},
"transactions": [
{
"amount": {
"total": "7.47",
"currency": "USD",
"details": {
"tax": "0.03",
"shipping": "0.03"
}
},
"description": "This is the payment transaction description.",
"related_resources": [
{
"sale": {
"id": "4RR959492F879224U",
"create_time": "2013-01-31T04:12:02Z",
"update_time": "2013-01-31T04:12:04Z",
"state": "completed",
"amount": {
"total": "7.47",
"currency": "USD"
},
"parent_payment": "PAY-17S8410768582940NKEE66EQ",
"links": [
{
"href": "https://api.sandbox.paypal.com/v1/payments/sale/4RR959492F879224U",
"rel": "self",
"method": "GET"
},
{
"href": "https://api.sandbox.paypal.com/v1/payments/sale/4RR959492F879224U/refund",
"rel": "refund",
"method": "POST"
},
{
"href": "https://api.sandbox.paypal.com/v1/payments/payment/PAY-17S8410768582940NKEE66EQ",
"rel": "parent_payment",
"method": "GET"
}
]
}
}
]
}
],
"links": [
{
"href": "https://api.sandbox.paypal.com/v1/payments/payment/PAY-17S8410768582940NKEE66EQ",
"rel": "self",
"method": "GET"
}
]
}
UPDATE: 我現在可以提取銷售ID,但感覺像是一個黑客。有沒有更好的辦法:
JSONObject obj = new JSONObject(input.toString());
String temp = obj.getJSONArray("transactions").getJSONObject(0)
.getJSONArray("related_resources").getJSONObject(0)
.toString();
JSONObject obj2 = new JSONObject(temp);
String temp2 = obj2.getJSONObject("sale").getString("id");
System.out.println(temp);
System.out.println(temp2);
你使用哪個庫? (是傑克遜?) –
'transactions'是一個數組 - 你需要迭代它的每個元素並從每個元素獲取'related_resources'。 – RobP