我知道有重复的问题。尽管如此,我无法弄清楚这一点。
以下是我从API收到的JSON文件。我需要得到#34;年"值。
我得到的错误是:
message org.glassfish.jersey.server.ContainerException:org.json.JSONException:找不到JSONArray [1]。
与Java上的这一行有关:
JSONObject year = years.getJSONObject(1).getJSONObject("years");
我也尝试过:
JSONObject year = years.getJSONObject(1);
为什么这段代码不起作用? index 1
数组中是否year
明确years
?
JSON
{
"make": {
"id": 200000404,
"name": "Chevrolet",
"niceName": "chevrolet"
},
"model": {
"id": "Chevrolet_Camaro",
"name": "Camaro",
"niceName": "camaro"
},
"drivenWheels": "rear wheel drive",
"numOfDoors": "2",
"options": [],
"colors": [],
"manufacturerCode": "1EH67",
"price": {
"baseMSRP": 34180.0,
"baseInvoice": 32813.0,
"deliveryCharges": 900.0,
"usedTmvRetail": 17766.0,
"usedPrivateParty": 16321.0,
"usedTradeIn": 14755.0,
"estimateTmv": false,
"tmvRecommendedRating": 0
},
"categories": {
"market": "Performance",
"EPAClass": "Compact Cars",
"vehicleSize": "Midsize",
"primaryBodyType": "Car",
"vehicleStyle": "Convertible",
"vehicleType": "Car"
},
"vin": "2G1FC3D33C9165616",
"squishVin": "2G1FC3D3C9",
"years": [{
"id": 100531911,
"year": 2012,
"styles": [{
"id": 101395591,
"name": "LT 2dr Convertible w/2LT (3.6L 6cyl 6M)",
"submodel": {
"body": "Convertible",
"modelName": "Camaro Convertible",
"niceName": "convertible"
},
"trim": "LT"
}]
}],
"matchingType": "SQUISHVIN",
"MPG": {
"highway": "28",
"city": "17"
}
}
JAVA
public String vehicleData(@PathParam("vin") String vin,
@PathParam("key") String key) throws Exception {
GetVehicleJSON jsonData = new GetVehicleJSON(vin, key);
JSONObject data = jsonData.getVehicleData();
String name = data.getJSONObject("make").getString("name");
String highway = data.getJSONObject("MPG").getString("highway");
String city = data.getJSONObject("MPG").getString("city");
JSONArray years = data.getJSONArray("years");
JSONObject year = years.getJSONObject(1).getJSONObject("years");
String s = year.getString("year");
return name + " " + s + " " + highway + " " + city;
}
答案 0 :(得分:3)
您正在使用索引从零开始的JSON数组。这样做:
JSONArray years = data.getJSONArray("years");
String year = years.getJSONObject(0).getString("year");
答案 1 :(得分:2)
你的json显示年份值是一个包含1个元素的数组,并且该元素内部是一个对象:
"years": [{ "id": 100531911, "year": 2012, "styles": [{ "id": 101395591, "name": "LT 2dr Convertible w/2LT (3.6L 6cyl 6M)", "submodel": { "body": "Convertible", "modelName": "Camaro Convertible", "niceName": "convertible" }, "trim": "LT" }] }],
因为数组元素编号从0开始,这意味着如果选择元素1,您将收到此错误:
message org.glassfish.jersey.server.ContainerException:org.json.JSONException:找不到JSONArray [1]。
要修复它,您需要选择元素0而不是1:
years.getJSONObject(0);