我的应用程序据说是发送源和目的地作为参数以获取最快的总线路由,然后将它们作为数组发送回。我想使用凌空抽射从JSON阵列中列出列表。这是我的数组输出的示例。
{
"arrayrute":[
"Halte LIK",
"Halte Kampoeng Semarang",
"Halte Kaligawe 2",
"Halte Pasar Kobong",
"Halte Kota Lama"
]
}
我应该如何从中列出清单?通常,来自数据库的JSON数组将在变量之前具有其行名称,因此我只需要使用list.set_id(jsonobject.getString("id"))
或list.set_id(jsonobject.optString("id"))
这是我的Java代码,要获得数组
private void getData() {
//Creating a string request
asal = spin_dari.getSelectedItem().toString().trim();
tujuan = spin_ke.getSelectedItem().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.GET, DIRECTION_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
results = j.getJSONArray("arrayrute");
//Calling method getStudents to get the students from the JSON Array
getdireksi(results);
//dirlist.add(results .toString());
} catch (JSONException e) {
e.printStackTrace();
}
adaptdir.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
})
{
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_ASAL,asal);
params.put(KEY_TUJUAN,tujuan);
return params;
}
};
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getdireksi(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
dirlist.add(json.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
请以这种方式尝试。以下是 demo
String url = "{ n" +
" "arrayrute":[ n" +
" "Halte LIK",n" +
" "Halte Kampoeng Semarang",n" +
" "Halte Kaligawe 2",n" +
" "Halte Pasar Kobong",n" +
" "Halte Kota Lama"n" +
" ]n" +
"}";
try {
JSONObject jobject= new JSONObject(url);
JSONArray jarray=jobject.getJSONArray("arrayrute");
for(int k=0;k<jarray.length();k++)
{
String getValue=(jarray.getString(k));
System.out.println("Intellij_Amiyo"+getValue);
}
} catch (JSONException e1) {
e1.printStackTrace();
}
final
private void getdireksi(JSONArray j)
{
//Traversing through all the items in the json array
for(int k=0;k<j.length();k++)
try {
String getValue=(j.getString(k));
System.out.println("Intellij_Amiyo"+getValue);
dirlist.add(json);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
您的getDireksi((方法是错误的。放下以下代码而不是您的代码。
private void getdireksi(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
String json = j.getString(i);
//Adding the name of the student to array list
dirlist.add(json);
} catch (JSONException e) {
e.printStackTrace();
}
}
}