任何幫助,將不勝感激......解析JSON陣列,而不是JSON對象
我是相當新的Android和Java的。我之前已經構建了一個應用程序,它將JSON對象中的JSON數組解析爲列表視圖。我在新應用程序中需要做的是解析JSON對象中未包含的JSON數組,並且無法弄清楚如何修改我的代碼。
Java Activity:
public class StationListActivity extends AppCompatActivity {
ListView mainListView;
JSONAdapter mJSONAdapter;
private static final String QUERY_URL = "url.json";
ProgressDialog mDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_station_list);
// Access the ListView
mainListView = (ListView) findViewById(R.id.list);
// Create a JSONAdapter for the ListView
mJSONAdapter = new JSONAdapter(this, getLayoutInflater());
// Set the ListView to use the ArrayAdapter
mainListView.setAdapter(mJSONAdapter);
mDialog = new ProgressDialog(this);
mDialog.setMessage("Searching");
mDialog.setCancelable(false);
// Create a client to perform networking
AsyncHttpClient client = new AsyncHttpClient();
// Show ProgressDialog to inform user that a task in the background is occurring
mDialog.show();
// Have the client get a JSONArray of data
// and define how to respond
client.get(QUERY_URL, new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONObject jsonObject) {
// Dismiss the ProgressDialog
mDialog.dismiss();
// update the data in your custom method.
mJSONAdapter.updateData(jsonObject.optJSONArray("-Here I would have JSON Object name which contained JSON Array-"));
}
@Override
public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
// Dismiss the ProgressDialog
mDialog.dismiss();
// Display a "Toast" message
// to announce the failure
Toast.makeText(getApplicationContext(), "Network error, please close app and try again", Toast.LENGTH_LONG).show();
// Log error message
// to help solve any problems
Log.e("applog", statusCode + " " + throwable.getMessage());
}
}
);
}
例JSON:
[
{
"name": "Silver",
"id": 12,
"number": 34
}
]
。 。 。
例JSON我知道如何處理:
{"title":
[
{
"name": "Silver",
"id": 12,
"number": 34
}
]
}
它可能不是最乾淨的解決辦法,但將有可能增加一些Java來檢索JSON分配給一個JSON對象作爲我的第二個例子?
因此,您習慣於使用JSON對象,其中鍵是名稱,值是JSON對象的JSON數組,對嗎?你所要做的就是通過迭代JSONArray中的每個元素來訪問你現在得到的json數組響應中的每個JSON對象。如有必要,我可以給你一個例子 –
如果可以的話,那將會很棒。 – dmca
基本上所有需要的就是調用新的JSONArray(String jsonFile),然後用for循環遍歷數組。 – geokavel