我試圖製作一個從Android上的url獲取數據的應用程序。我注意到JSON文件是不同的。他們中的一些人從一個陣式名稱開始,而另一些則沒有。那些具有數組名稱like this哪些「用戶」是數組名稱在我的應用程序中工作,但那些沒有任何數組名稱不起作用。 For example this。如何在JSON文件沒有任何對象時創建數組,並且只有對象
這是我儘量讓數組對象的代碼,但它不會爲第二JSON文件工作,因爲它沒有找到數組名稱:
//URL to get JSON Array
private static String url = "http://api.worldbank.org/countries/ir?format=json";
//JSON Node Names
private static final String TAG_USER = "user";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
JSONArray user = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting JSON Array
user = json.getJSONArray(TAG_USER);
JSONObject c = user.getJSONObject(0);
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
//Importing TextView
final TextView uid = (TextView)findViewById(R.id.uid);
final TextView name1 = (TextView)findViewById(R.id.name);
final TextView email1 = (TextView)findViewById(R.id.email);
//Set JSON Data in TextView
uid.setText(id);
name1.setText(name);
email1.setText(email);
} catch (JSONException e) {
e.printStackTrace();
}
}
所以這個例子是第一個JSON部分。你能告訴我如何有類似的代碼,但第二個JSON文件嗎?
您對第二個文件中的哪些信息感興趣? – Octoshape
@Octoshape任何。我只想學習處理這種有數組而不是對象的文件。我會得到像id,name,region,iso2Code – user2977338
這樣的數據你使用JSONParser的learn2crack庫還是你自己寫了一個? – Octoshape