Java 如何为listView使用ArrayAdapter和JSONArray
到目前为止,我可以向服务器发送Get请求,并在url中添加一封信:Java 如何为listView使用ArrayAdapter和JSONArray,java,android,json,arraylist,Java,Android,Json,Arraylist,到目前为止,我可以向服务器发送Get请求,并在url中添加一封信: private void GetDevice() { String deviceId = editTextDeviceId.getText().toString().trim(); if(TextUtils.isEmpty(deviceId)){ editTextDeviceId.setError("Please enter deviceId"); editTextDevice
private void GetDevice() {
String deviceId = editTextDeviceId.getText().toString().trim();
if(TextUtils.isEmpty(deviceId)){
editTextDeviceId.setError("Please enter deviceId");
editTextDeviceId.requestFocus();
}
HashMap<String, String>params = new HashMap<>();
params.put("deviceID", deviceId);
PerformNetworkRequest request = new PerformNetworkRequest(Api.URL_GETBYDEVICEID + deviceId, null, CODE_GET_REQUEST);
request.execute();
}
服务器响应为JSONArray:
W/System.err: org.json.JSONException: Value [{"DeviceId":"T","TransactionValue":2,"RSSI":2,"Time":"2018-08-02T14:43:00"}] of type org.json.JSONArray cannot be converted to JSONObject
这是我的问题。
通过阅读,我知道我需要使用ArrayList和ArrayAdapter将其转换为JSONObject。到目前为止我说的对吗
这就是我被困的地方,因为我不知道怎么做
非常感谢 从服务器返回的JSON字符串是一个JSON数组 因此,您需要将其转换为Jsonarray,如下所示,这里的jsonString是返回的JSON字符串
试试看{
JSONArray数组=新的JSONArray(jsonString);
}捕获(JSONException e){
e、 printStackTrace();
}
您发送的参数是一个JSONArray
,服务器需要的参数是一个JSONObject
。
JSONObject
的结构类似于{}
,JSONArray
类似于[{},{},…,{}]
。因此,您可以将参数更改为{“设备ID”:“T”,“事务值”:2,“RSSI”:2,“时间”:“2018-08-02T14:43:00”
或编辑服务器的代码以使用JSONArray
接收参数
您需要添加阵列适配器
ArrayList<String> items = new ArrayList<String>();
for(int i=0; i < jArray.length() ; i++) {
json_data = jArray.getJSONObject(i);
String deviceID=json_data.getString("deviceID");
items.add(deviceID);
Log.d(deviceID,"Output"+deviceID);
}
ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item, items));
setListAdapter(mArrayAdapter);
ArrayList items=new ArrayList();
for(int i=0;i
在Hashmap中添加设备id它可以工作看起来你正在尝试将字符串json转换为JSONObject,但字符串结果是JSONArrayI意思是这是我理解的,但在这一点上我很困惑。你的列表数据适配器看起来怎么样?我希望可以,但我没有访问服务器的权限。另外,我发送的是GET请求而不是POST请求,所以我不发送参数。好吧,我搞错了。您可以尝试以下代码:
try{org.json.JSONArray JSONArray=new org.json.JSONArray(json);JSONObject object=JSONArray.getJSONObject(0);}catch(JSONException e){e.printStackTrace();}
是的,但您确定它不涉及ArrayAdapter?服务器返回json数组,您需要将其转换为数组适配器以在listview中显示,但这不是您遇到的问题。如何在listview中显示数据,请看这里,这就是您的错误所在,键入org.json.JSONArray无法转换为JSONObject谢谢。当你说在Hashmap中添加设备id时,你能更具体一点吗?我也不知道变量jArray,json_data是什么?对不起,我开始了,这对我来说不容易。
ArrayList<String> items = new ArrayList<String>();
for(int i=0; i < jArray.length() ; i++) {
json_data = jArray.getJSONObject(i);
String deviceID=json_data.getString("deviceID");
items.add(deviceID);
Log.d(deviceID,"Output"+deviceID);
}
ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item, items));
setListAdapter(mArrayAdapter);