当我在 post 方法上点击 api 时得到空对象响应

Posted

技术标签:

【中文标题】当我在 post 方法上点击 api 时得到空对象响应【英文标题】:Getting null object response when i hit the api on post method 【发布时间】:2019-11-18 17:19:51 【问题描述】:

我有一些 json 数据,我正在尝试通过 api 响应 json。但是当我试图得到回应时,每次 得到 W/System.err: org.json.JSONException: No value for cadet_details 这个错误在我的 android studio logcat 上。帮我怎么做 得到这个回应。

我的活动代码:-

private void ncccadetlist(int i)

        mHandler.sendEmptyMessage(SHOW_PROG_DIALOG);
        progress_dialog_msg = "loading...";

        String Url =  "http://www.tsassessors.in/nccwork/API/cadre_sign_up_login/getApprovedCadetsListByInstitute.php";
        StringRequest stringRequest = new StringRequest(Request.Method.GET, Url,

                new Response.Listener<String>() 
                    @Override
                    public void onResponse(String s) 

                        try 
                            JSONObject json = new JSONObject(s);
                            Log.d("status", s);
                            String status = json.getString("status");
                            String msg = json.getString("msg");


                            if (json.getString("status").equals("0")) 
                                Log.d("step1", "cadets");
                                JSONArray jsonArray = json.getJSONArray("cadet_details");


                                for (int i = 0; i < jsonArray.length(); i++) 
                                    JSONObject localJson = jsonArray.getJSONObject(i);
                                    CadetDetail cadetDetail = new CadetDetail();
                                    cadetDetail.setCadetName(localJson.getString("cadet_name"));
                                    cadetDetail.setEnrollmentNo(localJson.getString("enrollment_no"));
                                    cadetDetail.setIsIsoUploaded(localJson.getString("is_iso_uploaded"));

                                    cadetDetailsArray.add(cadetDetail);

                                    progress_dialog.dismiss();

                                


                                /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                             else 
                                FancyToast.makeText(context, "" + msg , FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show();
                            

                         catch (JSONException e) 
                            e.printStackTrace();
                        
                    
                ,
                new Response.ErrorListener() 
                    @Override
                    public void onErrorResponse(VolleyError volleyError) 

                        FancyToast.makeText(context,"Some issue in loading",FancyToast.LENGTH_LONG,FancyToast.ERROR,false).show();
                    
                ) 
            @Override
            protected Map<String, String> getParams() throws AuthFailureError 

                Map<String, String> params = new Hashtable<String, String>();

                Log.d("Final", "history of api");
                params.put("instt_id", insttId );
                params.put("ncc_year", "2" );




                return params;
            
        ;
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    

CadetDetail.java

package com.tsa.ncc_dte_punjab.models;

import java.util.HashMap;
import java.util.Map;


public class CadetDetail 


    private String cadetName;

    private String status;

    private String msg;

    private String enrollmentNo;

    private String isIsoUploaded;

    private Map<String, Object> additionalProperties = new HashMap<String, Object>();


    public String getCadetName() 
        return cadetName;
    


    public void setCadetName(String cadetName) 
        this.cadetName = cadetName;
    


    public String getEnrollmentNo() 
        return enrollmentNo;
    


    public void setEnrollmentNo(String enrollmentNo) 
        this.enrollmentNo = enrollmentNo;
    


    public String getIsIsoUploaded() 
        return isIsoUploaded;
    


    public void setIsIsoUploaded(String isIsoUploaded) 
        this.isIsoUploaded = isIsoUploaded;
    


    public Map<String, Object> getAdditionalProperties() 
        return this.additionalProperties;
    

    public String getStatus() 
        return status;
    

    public void setStatus(String status) 
        this.status = status;
    

    public String getMsg() 
        return msg;
    

    public void setMsg(String msg) 
        this.msg = msg;
    

    public void setAdditionalProperty(String name, Object value) 
        this.additionalProperties.put(name, value);
    


JSON 响应:-


    "status": "1",
    "cadet_details": [
        
            "cadet_name": "AJIT SINGH",
            "enrollment_no": "",
            "is_iso_uploaded": "0"
        ,
        
            "cadet_name": "AKASH",
            "enrollment_no": "",
            "is_iso_uploaded": "0"
        ,
        
            "cadet_name": "AKASH",
            "enrollment_no": "",
            "is_iso_uploaded": "0"
        ,
        
            "cadet_name": "AKASH ",
            "enrollment_no": "",
            "is_iso_uploaded": "0"
        ,

]

错误:

2019-07-09 12:58:22.243 11818-11818/com.tsa.ncc_dte_punjab W/.ncc_dte_punjab: type=1400 audit(0.0:79109): avc: denied  getattr  for path="/dev/sw_sync" dev="tmpfs" ino=6638 scontext=u:r:untrusted_app:s0:c512,c768 tcontext=u:object_r:sw_sync_device:s0 tclass=chr_file permissive=0
2019-07-09 12:58:22.250 11818-11818/com.tsa.ncc_dte_punjab D/status:  
    "status":"0","msg":"Please select NCC Year"
2019-07-09 12:58:22.250 11818-11818/com.tsa.ncc_dte_punjab D/step1: cadets
2019-07-09 12:58:22.250 11818-11818/com.tsa.ncc_dte_punjab W/System.err: org.json.JSONException: No value for cadet_details
2019-07-09 12:58:22.256 11818-11818/com.tsa.ncc_dte_punjab W/System.err:     at org.json.JSONObject.get(JSONObject.java:389)
2019-07-09 12:58:22.256 11818-11818/com.tsa.ncc_dte_punjab W/System.err:     at org.json.JSONObject.getJSONArray(JSONObject.java:584)
2019-07-09 12:58:22.256 11818-11818/com.tsa.ncc_dte_punjab W/System.err:     at com.tsa.ncc_dte_punjab.activities.AttendanceActivity$5.onResponse(AttendanceActivity.java:327)
2019-07-09 12:58:22.256 11818-11818/com.tsa.ncc_dte_punjab W/System.err:     at com.tsa.ncc_dte_punjab.activities.AttendanceActivity$5.onResponse(AttendanceActivity.java:314)
2019-07-09 12:58:22.256 11818-11818/com.tsa.ncc_dte_punjab W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:82)
2019-07-09 12:58:22.256 11818-11818/com.tsa.ncc_dte_punjab W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:29)
2019-07-09 12:58:22.256 11818-11818/com.tsa.ncc_dte_punjab W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
2019-07-09 12:58:22.256 11818-11818/com.tsa.ncc_dte_punjab W/System.err:     at android.os.Handler.handleCallback(Handler.java:836)
2019-07-09 12:58:22.257 11818-11818/com.tsa.ncc_dte_punjab W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:103)
2019-07-09 12:58:22.257 11818-11818/com.tsa.ncc_dte_punjab W/System.err:     at android.os.Looper.loop(Looper.java:203)
2019-07-09 12:58:22.257 11818-11818/com.tsa.ncc_dte_punjab W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6251)
2019-07-09 12:58:22.257 11818-11818/com.tsa.ncc_dte_punjab W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
2019-07-09 12:58:22.257 11818-11818/com.tsa.ncc_dte_punjab W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
2019-07-09 12:58:22.257 11818-11818/com.tsa.ncc_dte_punjab W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
I am trying to help by Editing , Just change the Method Of Request
 from GET to POST because GET not Passing any Parameter 
with Request so that response will be status 0

the another thing int insttId = 1; 
define some where in your code your will get success response with status 1. ```


【问题讨论】:

您发布的 json 响应是正确的。在此处检查您的 json 响应 https://jsonlint.com/ 你有没有为此提供任何参数? 【参考方案1】:

只需改变这个-:

json.getString("status").equals("0")

到:

json.getString("status").equals("1")

【讨论】:

【参考方案2】:

您没有正确加载 JSON 文件。使用这个:

try 
            JSONObject obj = null;

          obj = new JSONObject(FileUtils.readFileRoot(AppConstants.CONFIG_FILE_NAME, this));
 //Load the config file


catch (JSONException e) 
            Crashlytics.getInstance().core.logException(e);
//            Issue #627
//            added the catch exception to check the config and throwing back to setup activity
            Toast.makeText(getApplicationContext(), "JsonException" + e, Toast.LENGTH_LONG).show();
            showAlertDialogButtonClicked(e.toString());
        

我的配置文件声明是:

 public static String CONFIG_FILE_NAME = "config.json";

如果有用请点赞!

【讨论】:

【参考方案3】:

首先:这是一个 GET 请求,而不是您在代码中提到的 POST。

 StringRequest stringRequest = new StringRequest(Request.Method.GET, Url,

第二:对于 GET 请求,api 返回这个 json 响应

"status":"0","msg":"Please select NCC Year"

在此响应中不包含 cadet_details 对象。

您需要像这样更改您的代码:

try 
                        JSONObject json = new JSONObject(s);
                        Log.d("status", s);
                        String status = json.getString("status");

                        if (!status.equals("0")) 
                            Log.d("step1", "cadets");
                            JSONArray jsonArray = json.getJSONArray("cadet_details");


                            for (int i = 0; i < jsonArray.length(); i++) 
                                JSONObject localJson = jsonArray.getJSONObject(i);
                                CadetDetail cadetDetail = new CadetDetail();
                                cadetDetail.setCadetName(localJson.getString("cadet_name"));
                                cadetDetail.setEnrollmentNo(localJson.getString("enrollment_no"));
                                cadetDetail.setIsIsoUploaded(localJson.getString("is_iso_uploaded"));

                                cadetDetailsArray.add(cadetDetail);

                                progress_dialog.dismiss();

                            


                            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                         else 
                         String msg = json.getString("msg");

                            FancyToast.makeText(context, "" + msg , FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show();
                        

                     catch (JSONException e) 
                        e.printStackTrace();
                    

【讨论】:

以上是关于当我在 post 方法上点击 api 时得到空对象响应的主要内容,如果未能解决你的问题,请参考以下文章

RestKit POST 对象到服务器,但服务器收到空的 GET 请求

保存对象上的休眠空指针

运行 post 方法时获取 get 方法

在 axios GET 请求中获取空对象

React js 和 axios POST 请求发送空数组

当我调用 post 方法时反应原生 Axios 或 fetch(get 方法工作正常) post 参数在服务器端获取空数据