Android 如何修复凌空库中的JSONException错误?
我试图发送一个带有两个参数的JSON对象请求,并试图从api调用中获取一个数组作为响应。但是,我在错误侦听器中遇到异常解析错误。单击按钮时会发送post请求。func接受两个参数,但无法获得响应,该函数直接转到on response error listenerAndroid 如何修复凌空库中的JSONException错误?,android,arrays,json,android-volley,Android,Arrays,Json,Android Volley,我试图发送一个带有两个参数的JSON对象请求,并试图从api调用中获取一个数组作为响应。但是,我在错误侦听器中遇到异常解析错误。单击按钮时会发送post请求。func接受两个参数,但无法获得响应,该函数直接转到on response error listener private void validate_log(String num) { /*buttonNumCheck.setVisibility(View.INVISIBLE); final ProgressBar pBar
private void validate_log(String num) {
/*buttonNumCheck.setVisibility(View.INVISIBLE);
final ProgressBar pBar=(ProgressBar)findViewById(R.id.progressBarLogin);
pBar.setVisibility(View.VISIBLE);*/
buttonNumCheck.setInProgress(true);
buttonNumCheck.setEnabled(false);
final String Org_id="81";
final String url="http://xya/api";
RequestQueue rq=Volley.newRequestQueue(this);
JSONObject js=new JSONObject();
try {
js.put("parm1", num);
js.put("parm2", Org_id);
final String requestBody=js.toString();
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjReq=new JsonObjectRequest(
Request.Method.POST, url, js,
new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
buttonNumCheck.setEnabled(true);
buttonNumCheck.setInProgress(false);
String stresponse=response.toString();
Toast.makeText(getApplicationContext(),"REPOSE="+response,Toast.LENGTH_SHORT).show();
System.out.println("RESPONSE= "+response);
try {
JSONArray heroArray = response.getJSONArray("");
// Toast.makeText(DeviceCheck_Activity.this, "Welcome Back"+ [1], Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
Log.e("Error", "Response Error", e);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(DeviceCheck_Activity.this, "Response error= " + error, Toast.LENGTH_LONG).show();
/*mdToast=MDToast.makeText(getApplicationContext(), "Oops something went wrong!!",
Toast.LENGTH_SHORT, MDToast.TYPE_ERROR);
mdToast.show();*/
buttonNumCheck.setInProgress(false);
buttonNumCheck.setEnabled(true);
Log.e("Error", "Response Error", error);
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers=new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
jsonObjReq.setShouldCache(false);
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
rq.add(jsonObjReq);
}
private void validate_日志(字符串num){
/*buttonNumCheck.setVisibility(视图不可见);
最终ProgressBar pBar=(ProgressBar)findViewById(R.id.progressBarLogin);
pBar.setVisibility(View.VISIBLE)*/
按钮NumCheck.setInProgress(真);
buttonNumCheck.setEnabled(假);
最终字符串Org_id=“81”;
最终字符串url=”http://xya/api";
RequestQueue rq=Volley.newRequestQueue(this);
JSONObject js=新的JSONObject();
试一试{
js.put(“parm1”,num);
js.put(“parm2”,组织id);
最后一个字符串requestBody=js.toString();
}捕获(JSONException e){
e、 printStackTrace();
}
JsonObjectRequest JSONObjectReq=新的JsonObjectRequest(
Request.Method.POST、url、js、,
新的Response.Listener(){
公共void onResponse(JSONObject响应){
buttonNumCheck.setEnabled(真);
按钮NumCheck.setInProgress(假);
字符串stresponse=response.toString();
Toast.makeText(getApplicationContext(),“resose=“+response,Toast.LENGTH_SHORT).show();
System.out.println(“RESPONSE=“+RESPONSE”);
试一试{
JSONArray heroArray=response.getJSONArray(“”);
//Toast.makeText(DeviceCheck_Activity.this,“欢迎回来”+[1],Toast.LENGTH_LONG.show();
}捕获(JSONException e){
e、 printStackTrace();
Log.e(“错误”,“响应错误”,e);
}
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
Toast.makeText(DeviceCheck_Activity.this,“Response error=“+error,Toast.LENGTH_LONG).show();
/*mdToast=mdToast.makeText(getApplicationContext(),“哎呀,出了什么问题!!”,
Toast.LENGTH\u SHORT,MDToast.TYPE\u错误);
mdToast.show()*/
按钮NumCheck.setInProgress(假);
buttonNumCheck.setEnabled(真);
Log.e(“错误”、“响应错误”、错误);
}
}) {
@凌驾
公共映射getHeaders()引发AuthFailureError{
HashMap headers=新的HashMap();
headers.put(“内容类型”、“应用程序/json;字符集=utf-8”);
返回标题;
}
};
jsonObjReq.setShouldCache(false);
jsonObjReq.setRetryPolicy(新的DefaultRetryPolicy(20*1000,0,DefaultRetryPolicy.DEFAULT\u BACKOFF\u MULT));
rq.add(jsonObjReq);
}
我得到的错误响应是
com.android.volley.ParseError:org.json.JSONException:org.json.JSONArray类型的值[{“store_id”:11,“store_name”:“Gomati District Main store”},{“store_id”:13,“store_name”:“Main Seed store”}]无法转换为JSONObject
像这样使用JsonArrayRequest,因为您的响应是JsonArray
JsonArrayRequest jsonObjReq = new JsonArrayRequest(Request.Method.POST, url, js,
new Response.Listener<JSONArray>() {
public void onResponse(JSONArray response) {
buttonNumCheck.setEnabled(true);
buttonNumCheck.setInProgress(false);
String stresponse = response.toString();
try {
for (int i = 0; i < response.length(); i++) {
JSONObject object = response.getJSONObject(i);
String id = object.getString("store_id");
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("Error", "Response Error", e);
}
}
}
JsonArrayRequest-jsonObjReq=newjsonarrayrequest(Request.Method.POST,url,js,
新的Response.Listener(){
公共void onResponse(JSONArray响应){
buttonNumCheck.setEnabled(真);
按钮NumCheck.setInProgress(假);
字符串stresponse=response.toString();
试一试{
对于(int i=0;i
您的问题可以通过两种方式解决:
第一:)
使用JSONArrayRequest而不是jsonobjectrequest
JSONObjectRequest返回一个JSONObject响应,而您的响应是一个JSONArray,因此java无法转换它,应用程序崩溃
更改您的请求如下:
JSONArrayRequest jsonArrReq=new JSONArrayRequest(//changed
Request.Method.POST, url, js,
new Response.Listener<JSONArray>() {
public void onResponse(JSONArray response) {
JSONArray heroArray = response;//changeed
/* rest of your code */
} catch (JSONException e) {
e.printStackTrace();
Log.e("Error", "Response Error", e);
}
}
},
jsonArrReq.setShouldCache(false);
jsonArrReq.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
rq.add(jsonArrReq);
JSONArrayRequest jsonArrReq=新JSONArrayRequest(//已更改
Request.Method.POST、url、js、,
新的Response.Listener(){
公共void onResponse(JSONArray响应){
JSONArray heroArray=response;//已更改
/*代码的其余部分*/
}捕获(JSONException e){
e、 printStackTrace();
Log.e(“错误”,“响应错误”,e);
}
}
},
jsonArrReq.setShouldCache(false);
jsonArrReq.setRetryPolicy(新的DefaultRetryPolicy(20*1000,0,DefaultRetryPolicy.DEFAULT\u BACKOFF\u MULT));
rq.add(jsonArrReq);
第二:)
使用StringRequest而不是JSONObjectRequest。字符串请求返回一个字符串响应,它允许您对响应执行任何您想要的操作
更改您的请求如下:
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
JSONArray heroArray = new JSONArray(response);
/* rest of your code */
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", "Response Error", error);
/*rest of your code */
}
}) {
@Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : js.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", js, "utf-8");
return null;
}
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
}
stringRequest.setShouldCache(false);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
rq.add(stringRequest);
StringRequest-StringRequest=new-StringRequest(Request.Method.POST,url,new-Response.Listener()){
@凌驾
公共void onResponse(字符串响应){
JSONArray heroArray=新JSONArray(响应);
/*代码的其余部分*/
}
},new Response.ErrorListener(){
RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
//JSONArray jsonArray_1=new JSONArray(response);
System.out.println("RESPONSE= " + response);
JSONArray jsonArray=new JSONArray(response);
json_stringarr=new String[jsonArray.length()];
if(jsonArray.length()>0) {
for (int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
//String web_page=jsonObject1.getString("awb_no");
String store_id=jsonObject1.getString("store_id");
String store_name=jsonObject1.getString("store_name");
json_stringarr[i]=store_id+" - "+store_name;
Toast.makeText(getApplicationContext(), "RESPOBBSE= " + json_stringarr[i], Toast.LENGTH_SHORT).show();
System.out.println("JSON ARRAY=" + json_stringarr[i]);
System.out.println("JSON Object=" + jsonObject1);
}
}
else{
Toast.makeText(getApplicationContext(),"Login ceredentils are incorrect",Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
MDToast mdToast=MDToast.makeText(getApplicationContext(), "Something went wrong!!", Toast.LENGTH_SHORT, MDToast.TYPE_WARNING);
mdToast.show();
error.printStackTrace();
}
}) {
@Override
public byte[] getBody() {
// String body="{\"param1\":"+num+",\"param2\":\"81"\"}";
String body="{\"parm1\":"+num+",\"parm2\":\"81\"}";
return body.getBytes();
}
/*@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("param1", num);
params.put("param2", Org_id);
return params;
}*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers=new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};