簡體   English   中英

錯誤:org.json.JSONEXception:類型為java.lang.String的值訪問無法轉換為JSONObject

[英]error: org.json.JSONEXception: Value Access of type java.lang.String cannot be converted to JSONObject

我正在嘗試制作一個android登錄應用,如您所見,您可以使用登錄按鈕登錄。 它將向服務器發送POST請求,服務器將返回JSON數據。 我的應用收到了數據,但無法解析。 此后它什么也沒做,但是我首先要使它正常工作。 這是我的代碼:

MainActivity.java

public class MainActivity extends Activity {


private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
      sb.append((char) cp);
    }
    return sb.toString();
  }

  public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
      String jsonText = readAll(rd);
      JSONObject json = new JSONObject(jsonText);
      return json;
    } finally {
      is.close();
    }
  }

  private EditText inpUsername;
  private EditText inpPassword;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    inpUsername = (EditText) findViewById(R.id.inpUsername);
    inpPassword = (EditText) findViewById(R.id.inpPassword);

}

public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

public void checkLogin(View v)
{
    new DoLoginAsyncTask().execute();
}   

  private class DoLoginAsyncTask extends AsyncTask<String, Void, String> {      
    private ProgressDialog LoadingDialog;
    String response = "";

    String LoadingDialogLoggingIn = getResources().getString(R.string.logging_in);



    @Override
    protected void onPreExecute() {
        LoadingDialog = new ProgressDialog(MainActivity.this);
        LoadingDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        LoadingDialog.setMessage(LoadingDialogLoggingIn);
        LoadingDialog.setCancelable(false);
        LoadingDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
        String username = inpUsername.getText().toString();
        String password = inpPassword.getText().toString();

        // Creating HTTP client
        HttpClient httpClient = new DefaultHttpClient();

        // Creating HTTP Post
        HttpPost httpPost = new HttpPost("http://mysite/");

        // Building post parameters
        // key and value pair
        List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
        nameValuePair.add(new BasicNameValuePair("tag", "login"));
        nameValuePair.add(new BasicNameValuePair("username", username));
        nameValuePair.add(new BasicNameValuePair("password", password));

        // Url Encoding the POST parameters
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
        } catch (UnsupportedEncodingException e) {
            // writing error to Log
            e.printStackTrace();
            response = response+"printStackTrace";
        }

        // Making HTTP Request
        try {
            HttpResponse response = httpClient.execute(httpPost);

            // writing response to log
            Log.d("Http Response:", response.toString());
        } catch (ClientProtocolException e) {
            // writing exception to log
            e.printStackTrace();
            response = response+"ClientProtocolException";
        } catch (IOException e) {
            // writing exception to log
            e.printStackTrace();
            response = response+"IOException";
        } 

        try{
            JSONObject json = readJsonFromUrl("http://mysite/");
            System.out.println(json.toString());
            System.out.println(json.get("id"));
        } catch(IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }



        return response;
    }

    @Override
    protected void onPostExecute(String result) {
        LoadingDialog.dismiss();
        LoadingDialog = null;
        if(response != "") {
            Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
        }
    }




}

}

服務器上的PHP代碼:

<?php
header('Content-type: application/json; charset=utf-8');
if (isset($_REQUEST['tag']) && $_REQUEST['tag'] != '') {
$tag = $_REQUEST['tag'];
require 'config.php';
$response = array("tag" => $tag, "success" => 0, "error" => 0);
mysql_connect("$mysql_host", "$mysql_username", "$mysql_password") or die(mysql_error()); 
mysql_select_db("$mysql_db_name") or die(mysql_error());


if($tag='login') {
    if(isset($_REQUEST['username']) && $_REQUEST['username'] != '' && isset($_REQUEST['password']) && $_REQUEST['password'] != '') {
        $username = $_REQUEST['username'];
        $password = $_REQUEST['password'];
        $hash = md5($password);
        $search = mysql_query("SELECT * FROM users WHERE username='".$username."' AND password='".$hash."' AND active='1'") or die(mysql_error());
        $match  = mysql_num_rows($search);
        $result = mysql_fetch_array($search);
        if($match > 0) {
            $response['tag']="login";
            $response['success']="1";
            $response['error']="0"; 
            $response['uid']=$result['id'];
            $response['username']=$result['username'];
            $response['name']=$result['name'];
            $response['surname']=$result['surname'];
            $response['email']=$result['email'];
        } else {
            $response['tag']="login";
            $response['success']="0";
            $response['error']="10";
        }
    } else {
        //username or password not filled in
        $response['tag']="login";
        $response['success']="0";
        $response['error']="11";
    }
}



            echo json_encode($response);

} else {
echo 'Access denied';
}
?>

來自服務器的示例JSON響應:

{"tag":"login","success":"0","error":"10"}

我從LogCat得到的錯誤:

org.json.JSONException: Value Access of type java.lang.String cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:107)
at org.json.JSONObject.<init>(JSONObject.java:158)
at org.json.JSONObject.<init>(JSONObject.java:171)
at com.example.myapp.MainActivity.readJsonFromUrl(MainActivity.java:56)
at com.example.myapp.MainActivity$DoLoginAsyncTask.doInBackground(MainActivity.java:147)
at com.example.myapp.MainActivity$DoLoginAsyncTask.doInBackground(MainActivity.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:185)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
at java.lang.Thread.run(Thread.java:1019)

我希望你能幫助我解決我的問題。

您又回來了: Access denied這意味着您的if語句返回false。 我有一段時間沒有使用PHP ,但是if($tag='login')看起來不對,您的意思是if($tag=='login')嗎?

在Java上,帶有=的賦值將始終返回true,不確定在PHP上的行為是否不同。

PS:如果需要JSON,還應該返回有效的json錯誤對象,而不是Access Denied字符串。 例如有你的JSON響應包含"status"successfailure簡單地進行檢查。 這將使區分成功響應或失敗響應變得容易。

PPS:我看到您嘗試使用$response = array("tag" => $tag, "success" => 0, "error" => 0);嘗試$response = array("tag" => $tag, "success" => 0, "error" => 0); 因此,基本上在該處添加錯誤代碼或類似代碼,然后返回該錯誤代碼而不是字符串。

編輯您正在執行兩個請求,您知道嗎?

// Making HTTP Request
try {
    // Fist request! With your tag and username and more
    HttpResponse response = httpClient.execute(httpPost);

    // writing response to log
    Log.d("Http Response:", response.toString());
} catch (ClientProtocolException e) {
    // writing exception to log
    e.printStackTrace();
    response = response+"ClientProtocolException";
} catch (IOException e) {
    // writing exception to log
    e.printStackTrace();
    response = response+"IOException";
} 

try{
    // second request! No tag, username...
    JSONObject json = readJsonFromUrl("http://mysite/");
    System.out.println(json.toString());
    System.out.println(json.get("id"));
} catch(IOException e) {
    e.printStackTrace();
} catch (JSONException e) {
    e.printStackTrace();
}

進行更改,然后嘗試將其合並:

try {
    // Fist request! With your tag and username and more
    HttpResponse response = httpClient.execute(httpPost);

    // writing response to log
    Log.d("Http Response:", response.toString());
    // try to parse it to json
    JSONObject json = new JSONObject(response.toString());
    // do what ever you like...
} catch (ClientProtocolException e) {
    // writing exception to log
    e.printStackTrace();
    response = response+"ClientProtocolException";
} catch (IOException e) {
    // writing exception to log
    e.printStackTrace();
    response = response+"IOException";
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM