尝试连接到本地服务器时出现JSON异常

时间:2014-08-18 19:28:13

标签: java php android json jsonexception

在我的本地服务器中注册其他用户时,我收到以下错误:

08-18 14:53:28.510: W/System.err(1223):     org.json.JSONException: No value for success
08-18 14:53:28.560: W/System.err(1223):     at org.json.JSONObject.get(JSONObject.java:355)
08-18 14:53:28.590: W/System.err(1223):     at org.json.JSONObject.getString(JSONObject.java:515)
08-18 14:53:28.590: W/System.err(1223):     at com.example.skelotong.RegularUsercreation$ruc.doInBackground(RegularUsercreation.java:134)
08-18 14:53:28.600: W/System.err(1223):     at com.example.skelotong.RegularUsercreation$ruc.doInBackground(RegularUsercreation.java:1)
08-18 14:53:28.600: W/System.err(1223):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
08-18 14:53:28.630: W/System.err(1223):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
08-18 14:53:28.630: W/System.err(1223):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
08-18 14:53:28.640: W/System.err(1223):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
08-18 14:53:28.640: W/System.err(1223):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
08-18 14:53:28.650: W/System.err(1223):     at java.lang.Thread.run(Thread.java:841)

我不知道出了什么问题。这是我在java中注册用户的代码:

@SuppressLint("NewApi")
private class ruc extends AsyncTask<String, Integer, Boolean> {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
    final ProgressDialog pd = new ProgressDialog(RegularUsercreation.this);

    @SuppressLint("NewApi")
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        pd.setMessage("Please wait");
        pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pd.setCanceledOnTouchOutside(false);
        pd.setCancelable(false);
        pd.setIndeterminate(true);
        pd.show();
        System.out.println("1");
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
                System.out.println(TAG_SUCCESS);
        }

    @Override
    protected Boolean doInBackground(String... params) {

        System.out.println(2);

        // Importing all assets like buttons, text fields
        inputFullName = (EditText) findViewById(R.id.FullName2);
        inputEmail = (EditText) findViewById(R.id.Email2);
        inputPassword = (EditText) findViewById(R.id.Password2);
        inputUsername = (EditText) findViewById(R.id.Username2);
        dateofbirth = (EditText) findViewById(R.id.DOB2);
        zip = (EditText) findViewById(R.id.ZipCode2);
        btnRegister = (Button) findViewById(R.id.create2);
        btnLinkToLogin = (Button) findViewById(R.id.cancel2);
        registerErrorMsg = (TextView) findViewById(R.id.errormessage3);
        // skils = (EditText) findViewById(R.id.skills1);
        System.out.println("3");

        // Register Button Click event

        String name = inputFullName.getText().toString();
        String email = inputEmail.getText().toString();
        String password = inputPassword.getText().toString();
        String usernmae = inputUsername.getText().toString();
        String birth = dateofbirth.getText().toString();
        String zipcode = zip.getText().toString();
        // String skills = skils.getText().toString();

        System.out.println(name + email + password + usernmae + birth
                + zipcode + 4 +TAG_SUCCESS);

        // check for login response
        // check for login response
        try {
            UserFunction userFunction = new UserFunction();
            JSONObject json = userFunction.registerUser(name, email,
                    password, usernmae, birth, zipcode,TAG_SUCCESS);
            //System.out.println(json.get(TAG_SUCCESS));
            if (json.optString(TAG_SUCCESS) != null) {

                String res = json.getString("success");
                System.out.println(91);
                System.out.println(res);

                if (Integer.parseInt(res) == 1) {
                    publishProgress(1);
                    // user successfully registred
                    // Store user details in SQLite Database
                    DatabaseHandler db = new DatabaseHandler(
                            getApplicationContext());
                    JSONObject json_user = json.getJSONObject("user");
                    System.out.println(6);
                    // Clear all previous data in database
                    userFunction.logoutUser(getApplicationContext());
                    db.addUser(json_user.getString(KEY_NAME),
                            json_user.getString(KEY_EMAIL),
                            json.getString(KEY_UID),
                            json_user.getString(KEY_CREATED_AT),
                            json_user.getString(KEY_USERNAME),
                            json_user.getString(KEY_password),
                            json_user.getString(KEY_ZIP),
                            json_user.getString(TAG_SUCCESS));
                    System.out.println("7");

                    return true;
                } else {

                    System.out.println("ERROR");
                    // Error in registration
                    registerErrorMsg
                            .setText("Error occured in registration");
                    return false;

                }
            } else {
                System.out.println(TAG_SUCCESS);
                return false;

            }
        } catch (JSONException e) {
            publishProgress(1);
            e.printStackTrace();
            System.out.println("9");
            System.out.println(e.toString());
            System.out.println(e.getCause());
            return false;
        } catch (RuntimeException e) {
            System.out.println("92");
            System.out.println(e.toString());
            System.out.println(e.getCause());
            return false;
        } catch (Exception e) {
            System.out.println("93");
            System.out.println(e.toString());
            System.out.println(e.getCause());
        }

        return false;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        // TODO Auto-generated method stub
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
        super.onProgressUpdate(values);
        if (values.equals(1)) {
            pd.setMessage("Almost Done");
        }
    }

以下是JSON的代码:

static BufferedReader is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() throws JSONException {

}
public  void JSONObject(java.lang.String source) {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> param) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("http://10.0.2.2/db_android/");
        HttpResponse httpResponse = httpClient.execute(httpPost);
        BufferedReader in = new BufferedReader(new InputStreamReader(
                httpResponse.getEntity().getContent(),"iso-8859-1"),8);
        is = in;

        System.out.println(json);
        /**
         * DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost
         * httpPost = new HttpPost(url);
         * 
         * HttpResponse httpResponse = httpClient.execute(httpPost);
         * HttpEntity httpEntity = httpResponse.getEntity(); is =
         * httpEntity.getContent();
         * 
         */
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("http://10.0.2.2/db_android/");
        HttpResponse httpResponse = httpClient.execute(httpPost);
        System.out.println(22);
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                httpResponse.getEntity().getContent(),"iso-8859-1"),8);
        System.out.println(22);
        StringBuilder sb = new StringBuilder();
        String line = null;
        System.out.println(33);
        while ((line = reader.readLine()) != null) {
            sb.append(line);
            System.out.println(44);
        }
        is.close();
        System.out.println(55);
        json = sb.toString();
        System.out.println(66);
        System.out.println(json);
        System.out.println(69);
        System.out.println(sb.toString());
        System.out.println(67);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }
    // try parse the string to a JSON object
    try {
        System.out.println(77);
        StringBuilder sb = new StringBuilder();
        json = sb.toString();
        Log.e("adsf", json.toString());
        Log.e("ads", json);
        System.out.println(79);
        jObj = new JSONObject("{"+json+"}");
        System.out.println(88);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
        e.getCause();
    }

    // return JSON String
    return jObj;

}

}

这是我在php中与所有内容相关的代码的另一部分:

} else if ($tag == 'register') {
    // Request type is Register new user
    $response ["success"] = 1;
    $response ["uid"] = $user ["unique_id"];
    $response ["user"] ["name"] = $user ["name"];
    $response ["user"] ["username"] = $user ["username"];
    $response ["user"] ["email"] = $user ["email"];
    $response ["user"] ["zipcode"] = $user ["zipcode"];
    $response ["user"] ["password"] = $user ["password"];
    $response ["user"] ["created_at"] = $user ["created_at"];
    $response ["user"] ["updated_at"] = $user ["updated_at"];
    $response ["user"] ["skills"] = $user ["skills"];
    // check if user is already existed
    if ($db->isUserExisted ( $email )) {
        // user is already existed - error response
        $response ["error"] = 2;
        $response ["error_msg"] = "User already existed";
        echo json_encode ( $response );
    } else if (! $db->validEmail ( $email )) {
        $response ["error"] = 3;
        $response ["error_msg"] = "Invalid Email Id";
        echo json_encode ( $response );
    } else {
        // store user
        $user = $db->storeUser ( $name, $email, $password, $unique_id, $dateofbirth, $zipcode, $skills, $username, $updated_at, $created_at );
        if ($user) {
            // user stored successfully

            $response ["uid"] = $user ["unique_id"];
            $response ["user"] ["name"] = $user ["name"];
            $response ["user"] ["username"] = $user ["username"];
            $response ["user"] ["email"] = $user ["email"];
            $response ["user"] ["zipcode"] = $user ["zipcode"];
            $response ["user"] ["password"] = $user ["password"];
            $response ["user"] ["created_at"] = $user ["created_at"];
            $response ["user"] ["updated_at"] = $user ["updated_at"];
            $response ["user"] ["skills"] = $user ["skills"];
            $response ["user"] ["uid"] = $user ["unique_id"];

            mail ( $email, $subject, $message, $headers );
            echo json_encode ( $response );
        } else {
            // user failed to store
            $response ["error"] = 1;
            $response ["error_msg"] = "JSON Error occured in Registartion";
            echo json_encode ( $response );
        }
    }
}

最后,这是我的数据功能之一:

public function storeUser($name, $email, $username, $password, $zipcode, $skills) {
    $uuid = uniqid('', true);
    $hash = $this->hashSSHA($password);
    $encrypted_password = $hash["encrypted"]; // encrypted password
    $salt = $hash["salt"]; // salt
    $result = mysql_query("INSERT INTO users(unique_id, name, email, username,   
 encrypted_password, salt, created_at) VALUES('$uuid', '$name', '$email',     '      
 $username','$zipcode', '$skills' '$encrypted_password', '$salt', NOW())");
    // check for successful store
    if ($result) {
        // get user details
        $uid = mysql_insert_id(); // last inserted id
        $result = mysql_query("SELECT * FROM users WHERE uid = $uid");
        // return user details
        return mysql_fetch_array($result);
    } else {
        return false;
    }
}

我很抱歉这篇文章中列出的所有代码。我不知道错误有多深,但我确实知道它在这些代码行之间。

String res = json.getString("success");
                System.out.println(91);
                System.out.println(res);
if (Integer.parseInt(res) == 1) {     //Line 134 of regular user creation as said in   
log cat

请以任何可能的方式帮助我。

1 个答案:

答案 0 :(得分:0)

这意味着成功密钥不存在。

每次设置错误时,都应将成功设置为false:

 $response ["success"] = 0;

JSON支持您应该使用它的布尔值(truefalse),它将使解析更容易。

Boolean res = json.getBoolean("success");
if(res){
  //success
}

您不必映射用户的每个属性,您可以通过直接存储用户对象来构建多维数组。

此外,您应该只在最后一次回显JSON,如果满足多个条件,这将避免无效的json。

您将拥有以下内容:

$response = array();
...
}else if ($tag == 'register') {

    // check if user is already existed
    if ($db->isUserExisted ( $email )) {
        $response ["success"] = false;
        $response ["error_msg"] = "User already existed";
        echo json_encode ( $response );
    } else if (! $db->validEmail ( $email )) {
        $response ["success"] = false;
        $response ["error_msg"] = "Invalid Email Id";
        echo json_encode ( $response );
    } else {
        // store user
        $user = $db->storeUser ( $name, $email, $password, $unique_id, $dateofbirth, $zipcode, $skills, $username, $updated_at, $created_at );
        if ($user) {
            // user stored successfully
            // Request type is Register new user
            $response ["success"] = true;
            $response ["user_data"] = $user;
            mail ( $email, $subject, $message, $headers );
            echo json_encode ( $response );
        } else {
            $response ["success"] = false;
            $response ["error_msg"] = "JSON Error occured in Registartion";

        }
    }
}
echo json_encode ( $response );