我有以下JSON。在这个JSON中,我将“ticketDetails”作为JSON数组。从这个数组我想在json对象“amount”中检索ticketPrice的值。我怎么能这样做?
{
"ticketDetails": [{
"seq": 1,
"qty": 2,
"amount": {
"ticketPrice": 120,
"bookingFee": 50
},
"session": {
"id": 1001,
"date": "2013, 9, 15",
"time": "1300"
},
"venue": {
"id": "MTRG",
"name": "Adlabs Manipur",
"companyCode": "ADLB"
},
"event": {
"id": "ET00000001123",
"name": "Chennai Express",
"producerCode": "YRF"
},
"category": {
"ttypeCode": "00012",
"areaCatCode": "2414",
"type": "Gold",
"price": 270
}
}]
}
任何建议都会有所帮助......
答案 0 :(得分:2)
以下是从给定的JSONObject中检索ticketPrice
的示例代码:
JSONObject objData = (JSONObject)JSONSerializer.toJSON(data);
JSONArray objTicketDetailsJsonArr = objData.getJSONArray("ticketDetails");
for(int nSize=0; nSize < objTicketDetailsJsonArr.size(); nSize++){
String ticketPrice = "";
ticketPrice = objTicketDetailsJsonArr.getString("ticketPrice");
}
以下是上述代码的导入:
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
答案 1 :(得分:1)
将数据存储在变量
中 data = {...}
然后你这样访问它:
data.ticketDetails[0].amount.ticketPrice
如果ticketDetails有多个元素
您可以遍历ticketDetails数组并将所有ticketPrice值存储在另一个数组ticketPriceArray
中以下内容在JavaScript中可以正常工作:
var ticketPriceArray = data.ticketDetails.map(function(k){
return k.amount.ticketPrice;
});
如果您正在使用其他编程语言,一般循环也可以正常工作
for ( i; i< ticketDetails.length ; i++){
ticketPriceArray[i] = data.ticketDetails.amount.ticketPrice[i];
}
对于Java,请查看本教程: http://answers.oreilly.com/topic/257-how-to-parse-json-in-java/
答案 2 :(得分:0)
你可以试试这段代码:
JsonObject transactiondata = (JsonObject)Offer.get("transData");
JsonObject ticketdata = (JsonObject)transactiondata.get("tickets");
JsonObject offerData = (JsonObject)Offer.get("offerData");
JsonObject offerData1 = (JsonObject)offerData.get("offerconfig");
JsonArray jsonarr= (JsonArray)ticketdata.get("ticketDetails");
double ticketPrice = Double.parseDouble(jsonarr.get(0).getAsJsonObject().get("amount").getAsJsonObject().get("ticketPrice").getAsString());
System.out.println("ticketPrice:"+ticketPrice);