2017-11-30 8 views
-2

아래 응답을 언급 할 때 안드로이드 프로젝트와 내 웹 서비스가 우편 배달부에서 성공적으로 응답하고 있습니다. API에서 응답을 얻은 후에 오류가 발생합니다. 처음으로 이러한 유형의 웹 서비스 호출을 수행하지는 않지만 왜 이런 일이 발생하는지 알지 못합니다. 이것을 어떻게 할 수 있습니까? 우편 배달부의android jsonarray가 jsonobject 오류로 변환 될 수 없습니다.

웹 서비스 응답 -

[ 
    { 
     "emp_id": 43065, 
     "emp_name": "Rahul Bhandari", 
     "username": "43065", 
     "password": null 
    } 
] 

오류 -

org.json.JSONException: Value [{"emp_id":43065,"emp_name":"Rahul Bhandari","username":"43065","password":null}] of type org.json.JSONArray cannot be converted to JSONObject 

발리 코드 -

public void apiCall(final String email, final String password) { 
     processArray = new ArrayList<String>(); 

     HashMap<String, String> params = new HashMap<String, String>(); 
     params.put("username", email); 
     params.put("password", password); 

     JsonObjectRequest request_json = new JsonObjectRequest(AppConfig.login, new JSONObject(params), 
       new Response.Listener<JSONObject>() { 
        @Override 
        public void onResponse(JSONObject response) { 

         if (mStatusCode == 200) { 
          try { 
           loginResult = new JSONArray(response.toString()); 


           try { 
            if (loginResult != null) { 
             for (int i = 0; i < loginResult.length(); i++) { 
              JSONObject obj = loginResult.getJSONObject(i); 
              // SQLite database handler 
              db = new SQLiteHandler(LoginActivity.this); 
              // Session manager 
              session = new SessionManager(LoginActivity.this); 
              session.setLogin(true); 
              // Inserting row in users table 
              db.addUser(obj.getString("username"), obj.getString("emp_name"), obj.getString("emp_id"), obj.getString("emp_designation"), obj.getString("emp_location")); 

              Intent intent = new Intent(LoginActivity.this, SelectAuditActivity.class); 
              startActivity(intent); 
              finish(); 

              Toast.makeText(LoginActivity.this, "Successfull login...", Toast.LENGTH_SHORT).show(); 

             } 
            } else { 
             Toast.makeText(LoginActivity.this, "Invalid login credential...", Toast.LENGTH_SHORT).show(); 
            } 

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

          } catch (JSONException e) { 
           e.printStackTrace(); 
          } 
          //Process os success response 
         } else { 
          Toast.makeText(LoginActivity.this, "Oops sorry something went wrong...", Toast.LENGTH_SHORT).show(); 
         } 
         //Process os success response 
        } 
       }, new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError error) { 
       VolleyLog.e("Error: ", error.getMessage()); 
      } 
     }) { 

      @Override 
      protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) { 
       mStatusCode = response.statusCode; 
       return super.parseNetworkResponse(response); 
      } 
     }; 
     ; 

     // add the request object to the queue to be executed 
     AppController.getInstance().addToRequestQueue(request_json); 
    } 

답변

-1

수익이 단지에서 웹 서비스

{ 
     "emp_id": 43065, 
     "emp_name": "Rahul Bhandari", 
     "username": "43065", 
     "password": null 
    } 
+0

onResponse()는 JsonObject를 수락하지만 웹 서비스에서 json array를 수락합니다. –

+0

게시물을 작성하기 전에 https://stackoverflow.com/help/how-to-answer를 읽어보십시오. – Kuls

1

귀하의 응답이 JSON 배열

[ 
{ 
    "emp_id": 43065, 
    "emp_name": "Rahul Bhandari", 
    "username": "43065", 
    "password": null 
} 
] 

하지만 당신이 JsonObjectRequest을 만들고, 마십시오 JsonArrayRequest 대신

편집 :

난 당신이 몸이 JSON 개체입니다 게시 참조

당신은 할 수 없습니다 JsonArrayRequest에 직접 Json 개체를 보내려면 getBody() 메서드를 사용하여 본문을 보내야합니다.

예 요청 JSONArray에 대한 표현 [ {...}, {...},.. ]

JsonArrayRequest jsObjRequest = new JsonArrayRequest 
      (requestMethod, url, null, new Response.Listener<JSONArray>() { 

       @Override 
       public void onResponse(JSONArray response) { 
        //do some thing with response 
       } 
      }, new Response.ErrorListener() { 

       @Override 
       public void onErrorResponse(VolleyError error) { 
        // handelErrorResponse 
       } 
      }) { 
     @Override 
     public Map<String, String> getHeaders() throws AuthFailureError { 
      return setHeaders(); 
     } 

     @Override 
     public byte[] getBody() { 

       String body; 
      // convert your json object to string and send it 
       body= yourJsonobject.toString(); 

       return body.getBytes(); 

     } 

     @Override 
     protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) { 
      getHeader(response); 
      return super.parseNetworkResponse(response); 
     } 
    }; 
    addToRequestQueue(jsObjRequest); 
0

이 대괄호. 따라서 배열에 하나의 항목 만있는 경우 JsonObjectRequestJsonArrayRequest으로 변경하면 JSONArray가 반환되고이 배열의 첫 번째 항목이 표시됩니다.

JsonArrayRequest req = new JsonArrayRequest(urlJsonArry, 
       new Response.Listener<JSONArray>() { 
        @Override 
        public void onResponse(JSONArray response) { 
         JSONObject result = response.get(0); 
       } 
} 
1
JsonArrayRequest request_json = new JsonArrayRequest(AppConfig.login, new JSONArray(params), 
      new Response.Listener<JSONArray>() { 
       @Override 
       public void onResponse(JSONArray response) { 

나는 한 번 JsonArrayRequest와 JsonObjectRequest을 대체 내가이 시도하지만 당신이 도움이되기를 바랍니다하지 않았다 위처럼 교체 시도해야 생각합니다.

{ a: "a", b: "b" } 

하지만 서비스가 같이 JSON 배열로 응답 :

0

당신은 객체 JsonObjectRequest를 사용하여 요청을하고,이 요청이 같은 오브젝트 형식으로 JSON을 기대하고 있다는 것을 의미 :

[{a:"a", b:"b"} , {a:"a1", b:"b1"}] 

그래서 위해 당신이 JsonArrayRequest

0

사용이 대구를 사용하여 요청을하는 방법을 변경하여 오류를 제거하기 e

if (loginResult != null) { 
     //for (int i = 0; i < loginResult.length(); i++) { 
       JSONObject obj = loginResult.getJSONObject(0); 
      //JSONObject obj = loginResult.getJSONObject(i); 
      // SQLite database handler 
       db = new SQLiteHandler(LoginActivity.this); 
       // Session manager 
      session = new SessionManager(LoginActivity.this); 
      session.setLogin(true); 
      // Inserting row in users table 

      /*db.addUser(obj.getString("username"), obj.getString("emp_name"), obj.getString("emp_id"), obj.getString("emp_designation"), obj.getString("emp_location"));*/ 

      db.addUser(obj.getString("username"), obj.getString("emp_name"), obj.getString("emp_id"),"",""); 

      Intent intent = new Intent(LoginActivity.this, SelectAuditActivity.class); 
      startActivity(intent); 
      finish(); 

      Toast.makeText(LoginActivity.this, "Successfull login...", 
      Toast.LENGTH_SHORT).show(); 

      //} 
      } else { 
       Toast.makeText(LoginActivity.this, "Invalid login credential...", Toast.LENGTH_SHORT).show(); 
}