2017-06-20 62 views
-2

的反應是這樣的,我想從這個JSON字符串得到 & 消息,我不知道,怎麼做到這一點?:從服務器org.json.JSONException:類型org.json.JSONObject不能轉換到JSONArray

響應

{ 
"Response": { 
    "status": { 
     "type": "Success", 
     "message": "You are authorized to access" 
    }, 
    "data": { 
     "msg": "Data Found", 
     "user": { 
      "user_id": "1", 
      "user_full_name": "User", 
      "user_name": "Username" 
     } 
    } 
} 
} 

錯誤:

org.json.JSONException: Value {"Response":{"status":{"type":"Success","message":"You are authorized to access"},"data":{"msg":"Data Found","user":{"user_id":"1","user_full_name":"User","user_name":"username"}}}} of type org.json.JSONObject cannot be converted to JSONArray 

代碼

String resp = response.body().string(); 
         JSONArray arr = null; 
         try { 
          arr = new JSONArray(resp); 
         } catch (JSONException e) { 
          e.printStackTrace(); 
         } 
         JSONObject jObj = null; 
         try { 
          jObj = arr.getJSONObject(0); 
         } catch (JSONException e) { 
          e.printStackTrace(); 
         } 
         try { 
          String type = jObj.getString("type"); 
          String msg = jObj.getString("message"); 
          if(type == "Success"){ 
           Intent intent = new Intent(getApplicationContext(), MainActivity.class); 
           startActivity(intent); 
          }else{ 
           Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_SHORT).show(); 
          } 
         } catch (JSONException e) { 
          e.printStackTrace(); 
         } 

我想要從這個JSON按摩&狀態。有人請幫忙。

回答

0

試試這個,

try { 
    JSONObject obj=new JSONObject(result); 
    JSONObject obj_response=obj.getJSONObject("Response"); 
    JSONObject obj_status=obj_response.getJSONObject("status"); 

    String type=obj_status.getString("type"); 
    String message=obj_status.getString("message"); 

    Log.d("TAG"," type:"+type+" message:"+message); 

} catch (JSONException e) { 
    e.printStackTrace(); 
} 
0
/**This part of code works to get value of type & message**/ 

String resp = response.body().string(); 

try 
{ 
    JSONObject resp_jsonObject = new JSONObject(resp); 

    String responseString = resp_jsonObject.getJSONObject("Response"); 

    JSONObject response_jsonObject = new JSONObject(responseString); 

    String statusString = response_jsonObject.getJSONObject("status"); 

    JSONObject status_jsonObject = new JSONObject(statusString); 

    String type = login_jsonObject.getString("type"); 

    String message = login_jsonObject.getString("message"); 

} 
catch (JSONException e) 
{ 
    e.printStackTrace(); 
} 
相關問題