我在開發Android應用程序時遇到問題。我的問題是我不知道如何使用GSON解析來自URL的JSON代碼。我搜索了Google和SO大約一個小時左右,但沒有爲我工作。我在互聯網上找到的所有東西都提到自定義的JSON代碼,而不是來自URL的代碼。這是我有的一小部分數據。無法使用GSON解析JSONArray
{
"status": {
"error": "NO",
"code": 200,
"description": "none",
"message": "Request ok"
},
"geoLocation": {
"city_id": "147",
"city_long": "Saint-Laurent",
"region_short": "QC",
"region_long": "Quebec",
"country_long": "Canada",
"country_id": "43",
"region_id": "35"
},
"stations": [
{
"country": "Canada",
"price": "3.65",
"address": "3885, Boulevard Saint-Rose",
"diesel": "0",
"id": "33862",
"lat": "45.492367",
"lng": "-73.710915",
"station": "Shell",
"region": "Quebec",
"city": "Saint-Laurent",
"date": "3 hours agp",
"distance": "1.9km"
},
{
"country": "Canada",
"price": "3.67",
"address": "3885, Saint-Mary",
"diesel": "0",
"id": "33872",
"lat": "45.492907",
"lng": "-73.740715",
"station": "Shell",
"region": "Quebec",
"city": "Saint-Laurent",
"date": "3 hours agp",
"distance": "2.0km"
}
]
}
我是JSON/GSON的初學者,所以我需要一些幫助。這裏是我有:
try {
String sURL = "http://api.mygasfeed.com/stations/radius/(39.631439)/(-80.8005451)/(25)/reg/(price)/uc82wk25m0.json?callback=?";
URL url = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //may be an array, may be an object.
longitude = rootobj.get("price").getAsString();
latitude = rootobj.get("address").getAsString();
} catch (Exception e) {
e.printStackTrace();
}
我試過一個循環來解析數組,但失敗慘了。任何有關這個問題的幫助,高度讚賞。
------------------------------編輯-------------- --------------------------------- 對於不正確的JSON代碼,我感到非常抱歉。我已經更新了代碼,但仍然無法找出解決方案。
您的JSON是不正確檢查「(?」:?http://jsonlint.com/ –
它是怎麼失敗如果你有一個堆棧跟蹤,請添加它。到 –
你的問題使用一些在線JSON驗證 –