2015-12-01 2 views
-1

Здесь я пытаюсь отправить мой JSON массив MySQL database.When я запускаю этот код, я получаю эту ошибку:Ошибка JSONObject не может быть преобразован в JSONArray в android?

com.android.volley.ParseError: org.json.JSONException: Value {"msg":false,"status":false} of type org.json.JSONObject cannot be converted to JSONArray 

И вот мой код:

private void insertToDb() { 
     billType = (invEstSwitch.isChecked() ? textViewEstimate : textViewInvoice) 
       .getText().toString(); 
     try { 
      jsonObject.put("custInfo", custSelected.toString()); 
      jsonObject.put("invoiceNo", textViewInvNo.getText().toString()); 
      jsonObject.put("barcode", barCode.getText().toString()); 
      jsonObject.put("desc", itemDesc.getText().toString()); 
      jsonObject.put("weight", weightLine.getText().toString()); 
      jsonObject.put("rate", rateAmount.getText().toString()); 
      jsonObject.put("makingAmt", makingAmount.getText().toString()); 
      jsonObject.put("net_rate", netRate.getText().toString()); 
      jsonObject.put("itemTotal", itemtotal.getText().toString()); 
      jsonObject.put("vat", textViewVat.getText().toString()); 
      jsonObject.put("sum_total", textViewSum.getText().toString()); 
      jsonObject.put("bill_type", billType); 
      jsonObject.put("date", textViewCurrentDate.getText().toString()); 


     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     try { 
      itemSelectedJson.put(index, jsonObject); 
      index++; 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

     final JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.POST, INVEST_URL, itemSelectedJson, new Response.Listener<JSONArray>() { 
      @Override 
      public void onResponse(JSONArray response) { 
       Log.d("RESPONSE", response.toString()); 
      } 
     }, new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError error) { 
       Log.d("JSON ERROR", error.toString()); 
      } 
     }) { 
      @Override 
      public Map<String, String> getHeaders() throws AuthFailureError { 
       Map<String, String> headers = new HashMap<>(); 
       headers.put("Content-Type", "application/json; charset=utf-8"); 
       headers.put("Accept", "application/json"); 
       return headers; 
      } 
     }; 

     final RequestQueue queue = Volley.newRequestQueue(this); 
     queue.add(arrayRequest); 

    } 

Я также попытался отображения JSON массив внутри текстового вида. Он отображает следующий массив json.

[ 
    { 
     "custInfo": "Ujwal 9975022560", 
     "rate": "24000", 
     "weight": "21.00000", 
     "desc": "GENTS ANGTHI 22k NO STONE", 
     "makingAmt": "200", 
     "sum_total": "RS.104188.92", 
     "vat": "RS.2042.92", 
     "itemTotal": "51073", 
     "barcode": "BQSP78BB", 
     "net_rate": "24200", 
     "date": "2015-12-01", 
     "invoiceNo": "1", 
     "bill_type": "Estimate" 
    }, 
    { 
     "custInfo": "Ujwal 9975022560", 
     "rate": "24000", 
     "weight": "21.00000", 
     "desc": "GENTS ANGTHI 22k NO STONE", 
     "makingAmt": "200", 
     "sum_total": "RS.104188.92", 
     "vat": "RS.2042.92", 
     "itemTotal": "51073", 
     "barcode": "BQSP78BB", 
     "net_rate": "24200", 
     "date": "2015-12-01", 
     "invoiceNo": "1", 
     "bill_type": "Estimate" 
    } 
] 

Я тестировал этот массив json на json lint.Это действительный JSON. Как было предложено, я перешел на запрос объекта json.Now я получаю ответ, он говорит ОТВЕТ: {"msg":false,"status":false} Я получаю его на public void onResponse(JSONObject response) { Log.d("RESPONSE", response.toString()); } Что это значит?

private void insertToDb() { 
     billType = (invEstSwitch.isChecked() ? textViewEstimate : textViewInvoice) 
       .getText().toString(); 
     try { 
      jsonObject.put("custInfo", custSelected.toString()); 
      jsonObject.put("invoiceNo", textViewInvNo.getText().toString()); 
      jsonObject.put("barcode", barCode.getText().toString()); 
      jsonObject.put("desc", itemDesc.getText().toString()); 
      jsonObject.put("weight", weightLine.getText().toString()); 
      jsonObject.put("rate", rateAmount.getText().toString()); 
      jsonObject.put("makingAmt", makingAmount.getText().toString()); 
      jsonObject.put("net_rate", netRate.getText().toString()); 
      jsonObject.put("itemTotal", itemtotal.getText().toString()); 
      jsonObject.put("vat", textViewVat.getText().toString()); 
      jsonObject.put("sum_total", textViewSum.getText().toString()); 
      jsonObject.put("bill_type", billType); 
      jsonObject.put("date", textViewCurrentDate.getText().toString()); 


     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     try { 
      itemSelectedJson.put(index, jsonObject); 
      index++; 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     JSONObject jsonobj = new JSONObject(); 
     try { 
      jsonobj.put("itemarray",itemSelectedJson); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

     final JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.POST, INVEST_URL, jsonobj, new Response.Listener<JSONObject>() { 
      @Override 
      public void onResponse(JSONObject response) { 
       Log.d("RESPONSE", response.toString()); 

      } 
     }, new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError error) { 
       Log.d("JSONERROR",error.toString()); 
      } 
     }){ 
      @Override 
      public Map<String, String> getHeaders() throws AuthFailureError { 
       Map<String, String> headers = new HashMap<>(); 
       headers.put("Content-Type", "application/json; charset=utf-8"); 
       headers.put("Accept", "application/json"); 
       return headers; 
      } 
     }; 
final RequestQueue queue = Volley.newRequestQueue(this); 
     queue.add(objectRequest); 

    } 
+0

На какой линии становится вопрос? –

+0

Опубликовать logcat – Pankaj

+0

@ ρяσѕρєяK Я регистрирую ошибку внутри ответа об ошибке – AndroidNewBee

ответ

0

And I final got it to work this is my current code

private void insertToDb() throws JSONException{ 
     //createJsonArray(); 
     final String jsonArray = itemSelectedJson.toString().trim(); 

     StringRequest stringRequest = new StringRequest(Request.Method.POST, INVEST_URL, 


      new Response.Listener<String>() { 
       @Override 
       public void onResponse(String response) { 
        display.setText("This is the "+response); 
        Toast.makeText(AddInvEst.this, "This is the response"+response, Toast.LENGTH_LONG).show(); 
        Log.d("RESPONSE", response.toString().trim()); 
       } 
      }, 
      new Response.ErrorListener() { 
       @Override 
       public void onErrorResponse(VolleyError error) { 

       } 
      }){ 
     @Override 
     protected Map<String, String> getParams() throws AuthFailureError { 

      Map<String,String> params = new HashMap<>(); 
      params.put(KEY_JSONARRAY,jsonArray); 
      return params; 
     } 
    }; 

    RequestQueue requestQ =Volley.newRequestQueue(this); 
    requestQ.add(stringRequest); 

} 
3

Как и в журнале:

com.android.volley.ParseError: org.json.JSONException: Value {"msg":false,"status":false}

Средства Сервер возвращает JSONObject вместо JSONArray в строку ответа.

Итак, используйте JsonObjectRequest вместо JsonArrayRequest, чтобы сделать запрос волейбола.

+0

Я попытался сделать его JSONObject, но он дает ошибку JSONERROR: com.android.volley.ParseError: org.json.JSONException: Конец ввода символа 0 из – AndroidNewBee

+0

@AndroidNewBee: Показать последний код и новые журналы ошибок –

+0

Я обновил вопрос, пожалуйста, проверьте – AndroidNewBee

1

POST JSONArray не означает, что вам нужно вызвать запрос JsonArrayRequest.

Запрос зависит от типа ответа, который вы ожидаете. Вы должны проверить тип объекта, возвращаемый вашим веб-сервисом, а затем адаптировать свой запрос в соответствии с этим.

В вашем конкретном случае в журнале ошибок говорится, что вам нужно использовать JsonObjectRequest вместо JsonArrayRequest.

+0

Я уже использую запрос объекта Json, пожалуйста, проверьте обновленный код до конца. Я добавил текущий код. – AndroidNewBee

+2

Теперь я получаю ответ . Say RESPONSE: {"msg": false, "status": false} I получить его в public void onResponse (ответ JSONObject) { Log.d («RESPONSE», response.toString()); } – AndroidNewBee

+0

@AndroidNewBee отлично! – Stefano

Смежные вопросы