【问题标题】:Android Volly Parsing Error for Nested JSONObject嵌套 JSON 对象的 Android Volley 解析错误
【发布时间】:2020-07-06 09:27:52
【问题描述】:

我正在尝试通过 Android Volly 库发布 Json 数据,但出现错误。

这是我的 Json 身体,与 Postman 完美配合。

{
"fullName": "Mr X",
"fatherName": "Mr Y",
"motherName": "Mrs Z",
"nidNo": "34345",
"surveyDate": "2020-03-25",
"birthCertificateNo": "3435355",
"mobileNumber": "01834261758",
"dateOfBirth": "",
"gender": "Male",
"bloodGroup": "A+",
"numOfDaysSick": "23",
"numOfContInftPerson": "0",
"remarks": "Need Rest",
"physicalSymptoms": ",Runny nose,Sore throat",
"status": "User",
"isForeignVisitor": "false",
"isRead": "false",
"presentAddress": {
    "village": "Sonapur",
    "postOffice": "Noahat",
    "postCode": "1219",
    "upazila": "Sonaimuri",
    "district": "Noakhali",
    "division": "Chittagong"
},
"permanentAddress": {
    "village": "Sonapur",
    "postOffice": "Noahat",
    "postCode": "1234",
    "upazila": "Sonaimuri",
    "district": "Noakhali",
    "division": "Chittagong"
}}

但是当我尝试通过 Android Volly 的 Post 调用发送它时,我收到以下错误:

com.android.volley.ParseError: org.json.JSONException: Value Survey of type java.lang.String cannot be converted to JSONObject

这是我生成此 Json 主体的 Android 方法。

请注意:我可以使用此 Android 方法成功生成 Json 正文并将粘贴(从 Logcat)复制到 Postman,它工作正常。但是 Android Volly 给了我这样的错误。我的网址也可以,因为我手动测试过。

public void SendSurveyDataToServer(){

    customProgressBar.show();
    //--


    //-------------------------------




    JSONObject permanent_address = new JSONObject();
    try {
        permanent_address.put("village", village_pS);
        permanent_address.put("postOffice", post_office_pS);
        permanent_address.put("postCode", post_code_pS);
        permanent_address.put("upazila", upazilla_pS);
        permanent_address.put("district", district_pS);
        permanent_address.put("division", division_pS);


    } catch (JSONException e) {
        e.printStackTrace();
    }
    //--


    JSONObject present_address = new JSONObject();
    try {
        present_address.put("village", village_tS);
        present_address.put("postOffice", post_office_tS);
        present_address.put("postCode", post_code_tS);
        present_address.put("upazila", upazilla_tS);
        present_address.put("district", district_tS);
        present_address.put("division", division_tS);


    } catch (JSONException e) {
        e.printStackTrace();
    }
    //--

    if(numberofContactedPersonS.equals("Yes")){

        numberofContactedPersonS = "true";
    }else{

        numberofContactedPersonS = "false";
    }

    //--


    //--
    JSONObject parameters = new JSONObject();
    try {
        parameters.put("fullName", fullNameS);
        parameters.put("fatherName", fatherNameS);
        parameters.put("motherName", motherNameS);
        parameters.put("nidNo", nidNoS);
        parameters.put("surveyDate", "2020-03-25");
        parameters.put("birthCertificateNo", birthdayCertificateNoS);
        parameters.put("mobileNumber", mobileNoS);
        parameters.put("dateOfBirth", "");
        parameters.put("gender", gender_selectS);
        parameters.put("bloodGroup", blood_group_selectS);
        parameters.put("numOfDaysSick", sickDaysNoS);
        parameters.put("numOfContInftPerson", "0");
        parameters.put("remarks", remarksS);
        parameters.put("physicalSymptoms", physicalSymptomsS);
        parameters.put("status", statusS);
        parameters.put("isForeignVisitor", numberofContactedPersonS );
        parameters.put("isRead", "false");
        parameters.put("presentAddress", present_address);
        parameters.put("permanentAddress", permanent_address);





    } catch (JSONException e) {
        e.printStackTrace();
    }

    Log.d(classTag,parameters.toString());

    RequestQueue rq = Volley.newRequestQueue(this);
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
            (Request.Method.POST, ApiClass.server_path+ApiClass.saveSurvey, parameters, new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    String respo=response.toString();
                    Log.d(classTag,respo);
                    //iosDialog.cancel();
                    //Parse_signup_data(respo);

                    Log.e(classTag,respo);



                    if(respo.equalsIgnoreCase("Survey Info save Successfully")){


                        Toast.makeText(Survey.this,"Your survey submitted successfully. Thank you!",Toast.LENGTH_LONG).show();



                        //----------------------------------------

                    }else if(respo.equalsIgnoreCase("Survey Info already exits")){


                        Toast.makeText(Survey.this,"Survey info already exist with this NID and Birth Certificate Number!",Toast.LENGTH_LONG).show();

                    }else{

                        Toast.makeText(Survey.this,"There is an error while submitting your survey, please try again!",Toast.LENGTH_LONG).show();

                        Log.e(classTag,"There is an error while submitting your survey, please try again!");

                    }


                    customProgressBar.hide();



                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // TODO: Handle error

                   // Toast.makeText(MainActivity.this,"Can't connect with server! Please check your network connection.",Toast.LENGTH_LONG).show();
                    customProgressBar.hide();
                    Log.d(classTag,error.toString());
                }
            });
    jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(30000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    rq.getCache().clear();
    rq.add(jsonObjectRequest);


    //--------------

}

【问题讨论】:

    标签: android json android-volley jsonobjectrequest


    【解决方案1】:

    搜索了3天,发现问题是API响应。它以 byte 格式给了我 'Success''Failed',但我一直在检查 JSONObject 的响应> 或至少 字符串。 Postman 自动将字节数据转换为字符串并显示给我,因此我认为服务器正在以 string 格式给我 response

    但是,我通过 Volly 的 String Request 发送 Json 请求并跟踪响应。然后我发现是什么在搞乱我!我们的后端开发人员可能懒得用 String 或 Json 格式给出响应。

    我通过将 byte 转换为 string 得到了响应:

    String string = new String(response.data, StandardCharsets.UTF_8);
    

    这是我对此的修改:

    RequestQueue requestQueue = Volley.newRequestQueue(this);
        String URL = ApiClass.server_path+ApiClass.saveSurvey;
        final String requestBody = parameters.toString();
    
        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.i("VOLLEY", response);
                customProgressBar.hide();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("VOLLEY", error.toString());
                customProgressBar.hide();
            }
        }) {
            @Override
            public String getBodyContentType() {
                return "application/json; charset=utf-8";
            }
    
            @Override
            public byte[] getBody() throws AuthFailureError {
                try {
                    return requestBody == null ? null : requestBody.getBytes("utf-8");
                } catch (UnsupportedEncodingException uee) {
                    VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                    return null;
                }
            }
    
            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
    
                //customProgressBar.hide();
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                    String string = new String(response.data, StandardCharsets.UTF_8);
                    Log.e(classTag,string);
    
                   serverMsg = string;
                    showServerMsgNow = true;
                    Log.e(classTag,"Server msg : "+serverMsg+" server show : "+showServerMsgNow);
                   // ShowServerResponse();
    
    
                }
    
    
                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));
            }
        };
    
        requestQueue.add(stringRequest);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2020-11-03
      相关资源
      最近更新 更多