JSON 异常:值 <? java.lang.String 类型的无法转换为 JSONObject

Posted

技术标签:

【中文标题】JSON 异常:值 <? java.lang.String 类型的无法转换为 JSONObject【英文标题】:JSON exception: Value <? of type java.lang.String cannot be converted to JSONObject 【发布时间】:2018-02-22 00:56:08 【问题描述】:

我正在 android 上制作登录应用程序,我使用 asynctask 和 Json 通过服务器交换数据,但我收到此错误,我正在添加代码。请帮助大家

    class RegisterUser extends AsyncTask<Void, Void, String> 

        private ProgressBar progressBar;

        @Override
        protected String doInBackground(Void... voids) 
            //creating request handler object
            RequestHandler requestHandler = new RequestHandler();

            //creating request parameters
            HashMap<String, String> params = new HashMap<>();
            params.put("username", username);
            params.put("email", email);
            params.put("password", password);
            params.put("gender", gender);

            //returing the response
            return requestHandler.sendPostRequest(URLs.URL_REGISTER, 
        params);
        

        @Override
        protected void onPreExecute() 
            super.onPreExecute();
            //displaying the progress bar while user registers on the server
            progressBar = (ProgressBar) findViewById(R.id.progressBar);
            progressBar.setVisibility(View.VISIBLE);
        

        @Override
        protected void onPostExecute(String s) 
            super.onPostExecute(s);
            //hiding the progressbar after completion
            progressBar.setVisibility(View.GONE);
            Log.i("JSON Parser", s);
            try 
                //converting response to json object
                JSONObject obj = new JSONObject(s);
              //  Log.i("JSON Parser", obj);

                //if no error in response
                if (!obj.getBoolean("error")) 
                    Toast.makeText(getApplicationContext(), 
     obj.getString("message"), Toast.LENGTH_SHORT).show();

                    //getting the user from the response
                    JSONObject userJson = obj.getJSONObject("user");

                    //creating a new user object
                    User user = new User(
                            userJson.getInt("id"),
                            userJson.getString("username"),
                            userJson.getString("email"),
                            userJson.getString("gender")
                    );

                    //storing the user in shared preferences


     SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);

                    //starting the profile activity
                    finish();
                    startActivity(new Intent(getApplicationContext(), 
  ProfileActivity.class));
                 else 
                    Toast.makeText(getApplicationContext(), "Some error 
 occurred", Toast.LENGTH_SHORT).show();
                
             catch (JSONException e) 
                e.printStackTrace();
                Log.d("error is","this");
            
        
    

    //executing the async task
    RegisterUser ru = new RegisterUser();
    ru.execute();
   

有趣的是 下面的 log.i

  @Override
        protected void onPostExecute(String s) 
            super.onPostExecute(s);
            //hiding the progressbar after completion
            progressBar.setVisibility(View.GONE);
            Log.i("JSON Parser", s); 

给了我两个 php 文件的源代码

我的php文件在下面

<?php

require_once 'DbConnect.php';

//an array to display response
$response = array();
mysqli_set_charset($con, 'utf8');
//if it is an api call 
//that means a get parameter named api call is set in the URL 
//and with this parameter we are concluding that it is an api call

if (isset($_GET['apicall'])) 

    switch ($_GET['apicall']) 

        case 'signup':
            //checking the parameters required are available or not 



            if (isTheseParametersAvailable
                            (array('username', 'email', 'password', 'gender'))) 

                //getting the values 
                $username = $_POST['username'];
                $email = $_POST['email'];
                $password = md5($_POST['password']);
                $gender = $_POST['gender'];

                //checking if the user is already exist with this username 
                or email
                //as the email and username should be unique for every user 
                $stmt = $conn->prepare("SELECT id FROM users WHERE username 
        = ? OR email = ?");
                $stmt->bind_param("ss", $username, $email);
                $stmt->execute();
                $stmt->store_result();

                //if the user already exist in the database 
                if ($stmt->num_rows > 0) 
                    $response['error'] = true;
                    $response['message'] = 'User already registered';
                    $stmt->close();
                 else 

                    //if user is new creating an insert query 
                    $stmt = $conn->prepare("INSERT INTO users (username, 
        email, password, gender) VALUES (?, ?, ?, ?)");
                    $stmt->bind_param("ssss", $username, $email, $password, $gender);

                    //if the user is successfully added to the database 
                    if ($stmt->execute()) 

                        //fetching the user back 
                        $stmt = $conn->prepare("SELECT id, id, username, 
          email, gender FROM users WHERE username = ?");
                        $stmt->bind_param("s", $username);
                        $stmt->execute();
                        $stmt->bind_result($userid, $id, $username, $email, $gender);
                        $stmt->fetch();

                        $user = array(
                            'id' => $id,
                            'username' => $username,
                            'email' => $email,
                            'gender' => $gender
                        );

                        $stmt->close();

                        //adding the user data in response 
                        $response['error'] = false;
                        $response['message'] = 'User registered 
               successfully';
                        $response['user'] = $user;
                    
                
             else 
                $response['error'] = true;
                $response['message'] = 'required parameters are not 
            available';
            

            break;

        case 'login':
            //for login we need the username and password 
            if (isTheseParametersAvailable(array('username', 'password'))) 
                //getting values 
                $username = $_POST['username'];
                $password = md5($_POST['password']);

                //creating the query 
                $stmt = $conn->prepare("SELECT id, username, email, gender 
               FROM users WHERE username = ? AND password = ?");
                $stmt->bind_param("ss", $username, $password);

                $stmt->execute();

                $stmt->store_result();

                //if the user exist with given credentials 
                if ($stmt->num_rows > 0) 

                    $stmt->bind_result($id, $username, $email, $gender);
                    $stmt->fetch();

                    $user = array(
                        'id' => $id,
                        'username' => $username,
                        'email' => $email,
                        'gender' => $gender
                    );

                    $response['error'] = false;
                    $response['message'] = 'Login successfull';
                    $response['user'] = $user;
                 else 
                    //if the user not found 
                    $response['error'] = false;
                    $response['message'] = 'Invalid username or password';
                
            
            break;

        default:
            $response['error'] = true;
            $response['message'] = 'Invalid Operation Called';
    
 else 
    //if it is not api call 
    //pushing appropriate values to response array 
    $response['error'] = true;
    $response['message'] = 'Invalid API Call';


//displaying the response in json structure 
echo json_encode($response);

//function validating all the paramters are available
//we will pass the required parameters to this function 
function isTheseParametersAvailable($params) 

    //traversing through all the parameters 
    foreach ($params as $param) 
        //if the paramter is not available
        if (!isset($_POST[$param])) 
            //return false 
            return false;
        
    
    //return true if every param is available 
    return true;

我是 android 和 java 的新手,我自己学习。我在某个网站上找到了这段代码并试图执行它,但它给出了这个错误。 帮助

【问题讨论】:

请发布 userJson 内容 将你的字符串解析为 JSON 对象 检查您的错误日志并确保您正确解析。 我认为你的服务器上没有安装 PHP(因为你得到了&lt;?,这是 PHP 文件的开头) 这就是我在我的安卓显示器中得到的结果 【参考方案1】:

看起来您的 PHP 文件无效。它从&lt;? 开始,并在头部缺少php。因此,不要在 PHP 文件中使用 &lt;?,而是使用 &lt;?php

读取文件时,Apache(或您使用的任何 PHP 服务器)会读取它,但不会将其识别为 PHP 文件。因此,它只需将其内容作为响应发送即可将其作为文本文件处理。

【讨论】:

以上是关于JSON 异常:值 <? java.lang.String 类型的无法转换为 JSONObject的主要内容,如果未能解决你的问题,请参考以下文章

急!ssh+json 空指针异常(net.sf.json.JSONException: java.lang.NullPointerException)

从空 sharedpreference 中检索 json 数组时,java.lang.String 无法转换为 JSONObject 异常出现

ajax请求json数据异常:nested exception is net.sf.json.JSONException: java.lang.reflect.InvocationTargetExce

使用json发生java.lang.NoClassDefFoundError: net/sf/json/JSONObject异常的解决办法

线程“主”java.lang.OutOfMemoryError 中的异常:在 ArrayList 中添加值时发生 Java 堆空间错误 [重复]

阿里巴巴 fastjson-1.2.12.jar json解析异常java.lang.ClassFormatError: Invalid method Code length 66865 in cla