简体   繁体   English

错误:org.json.JSONEXception:类型为java.lang.String的值访问无法转换为JSONObject

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

I'm trying to make an android login app, and as you can see you can login using the login button. 我正在尝试制作一个android登录应用,如您所见,您可以使用登录按钮登录。 It will send a POST request to the server and the server will return JSON data. 它将向服务器发送POST请求,服务器将返回JSON数据。 My app receives the data but cannot parse it. 我的应用收到了数据,但无法解析。 It doesn't do anything after this, but I first want to get this working. 此后它什么也没做,但是我首先要使它正常工作。 Here is my code: 这是我的代码:

MainActivity.java 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 code on the server: 服务器上的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';
}
?>

example JSON response from server: 来自服务器的示例JSON响应:

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

The error I get from LogCat: 我从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)

I hope you can help me with my problem. 我希望你能帮助我解决我的问题。

You are getting back: Access denied meaning that your if statement returns false. 您又回来了: Access denied这意味着您的if语句返回false。 I am out of PHP for quite a while but if($tag='login') looks wrong, did you mean if($tag=='login') ? 我有一段时间没有使用PHP ,但是if($tag='login')看起来不对,您的意思是if($tag=='login')吗?

On Java an assignment with = would always return true, not sure if this behaves different on PHP. 在Java上,带有=的赋值将始终返回true,不确定在PHP上的行为是否不同。

PS: If you expect JSON, you should also return a valid json error object instead of a Access Denied String. PS:如果需要JSON,还应该返回有效的json错误对象,而不是Access Denied字符串。 For example having your json response contain "status" with success or failure to simply check for. 例如有你的JSON响应包含"status"successfailure简单地进行检查。 This would make it easy to differ between an successful response or a failed one. 这将使区分成功响应或失败响应变得容易。

PPS: I see you tried that with $response = array("tag" => $tag, "success" => 0, "error" => 0); PPS:我看到您尝试使用$response = array("tag" => $tag, "success" => 0, "error" => 0);尝试$response = array("tag" => $tag, "success" => 0, "error" => 0); so basically add the error code or similar there and return that instead of the string. 因此,基本上在该处添加错误代码或类似代码,然后返回该错误代码而不是字符串。

Edit You are doing two request, you know that? 编辑您正在执行两个请求,您知道吗?

// 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();
}

Change that and try to combine it: 进行更改,然后尝试将其合并:

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.

相关问题 解析数据org.json.JSONException时出错:值 - Error parsing data org.json.JSONException: Value <!— of type java.lang.String cannot be converted to JSONObject 错误。 org.json.JSONException:值 - error. org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject android错误org.json.JSONException:值 - android error org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject org.json.JSONException:值<HTML><HEAD> - org.json.JSONException: Value <HTML><HEAD><STYLE of type java.lang.String cannot be converted to JSONObject org.json.JSONException:类型为java.lang.String的值test(无法转换为JSONObject - org.json.JSONException: Value test( of type java.lang.String cannot be converted to JSONObject 如何解决org.json.JSONException:Value - How to solve the org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject org.json.JSONException:值<html><body> - org.json.JSONException: Value <html><body><script of type java.lang.String cannot be converted to JSONObject 如何修复:org.json.JSONException:类型java.lang.String的值不能转换为JSONObject - How to fix: org.json.JSONException: Value of type java.lang.String cannot be converted to JSONObject org.json.JSONException:值类型为java.lang.String的数据不能转换为JSONObject - org.json.JSONException: Value Data of type java.lang.String cannot be converted to JSONObject org.json.JSONException:java.lang.String 类型的值 HTTP 无法转换为 JSONObject - org.json.JSONException: Value HTTP of type java.lang.String cannot be converted to JSONObject
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM