我想解析這個:https://s3.amazonaws.com/dolartoday/data.json爲Android應用程序顯示美元兌玻利維亞非官方匯率。解析沒有陣列的JSON文件
我正在使用本教程:http://www.androidhive.info/2012/01/android-json-parsing-tutorial/,之前我已成功地使用過,但是之前使用的API包含一個JSON數組和子對象。然而,這個有12個帶字符串的JSON對象。沒有方括號可見。
的部分(我認爲)我有麻煩是:
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("contacts");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
}
我不是專家,因爲我想學習編程我自己,我還是很新的。但是,我做了一些更改,包括刪除ListView,並將代碼調整爲新的JSON。
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Object node
JSONObject c = jsonObj.getJSONObject("USD");
JSONObject d = jsonObj.getJSONObject("EUR");
String usdtrans = c.getString("dolartoday");
String usdreal = c.getString("efectivo_real");
String usddicom = c.getString("sicad2");
String eurtrans = d.getString("dolartoday");
String eurreal = d.getString("efectivo_real");
String eurdicom = d.getString("sicad2");
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
}
該代碼無法編譯,Android Studio檢測到"unhandled exception: org.json.JSONException"
。我能做些什麼來改變這一點?
任何幫助,將不勝感激。我的其他代碼也有其他問題,但我想我可以在完成這一步後將其排除。
您之前'抓(最終JSONException E)在你的第二個代碼'了不必要的大括號。 –
json:''dolartoday「:1026.13', code:'String usdtrans = c.getString(」dolartoday「);' 該json的值不是String。它是雙倍的。如果你getString,這將是錯誤的。 –
不,它不會。 double值將被轉換爲字符串並返回 –