【问题标题】:getting "java.lang.String cannot be converted to JSONObject" error how to correct it出现“java.lang.String 无法转换为 JSONObject”错误如何纠正
【发布时间】:2017-12-02 02:34:52
【问题描述】:

在我的应用中出现此错误

W/System.err: org.json.JSONException: java.lang.String 类型的值 br 无法转换为 JSONObject

这是我的 RegisterActivity.java

public class RegisterActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    final EditText etName=(EditText) findViewById(R.id.etname);
    final EditText etUsername=(EditText) findViewById(R.id.etusername);
    final EditText etPassword=(EditText) findViewById(R.id.etpassword);
    final EditText etCPassword=(EditText) findViewById(R.id.etcpassword);
    final EditText etEmail=(EditText) findViewById(R.id.etemail);
    final EditText etContact=(EditText) findViewById(R.id.etcontact);
    final EditText etAge=(EditText) findViewById(R.id.etage);
    final Button btnRegister=(Button) findViewById(R.id.btnregister);

    btnRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String name=etName.getText().toString();
            final String username=etUsername.getText().toString();
            final String password=etPassword.getText().toString();
            final String email=etEmail.getText().toString();
            final int age=Integer.parseInt(etAge.getText().toString());
            final int contact=Integer.parseInt(etContact.getText().toString());

            Response.Listener<String> responseListener = new Response.Listener<String>(){

                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse= new JSONObject(response);
                        boolean success = jsonResponse.getBoolean("success");

                        if(success){
                            Intent intent = new Intent(RegisterActivity.this,LoginActivity.class);
                            RegisterActivity.this.startActivity(intent);
                        }else{
                            AlertDialog.Builder builder= new AlertDialog.Builder(RegisterActivity.this);
                            builder.setMessage("Register Failed")
                                    .setNegativeButton("Retry",null)
                                    .create()
                                    .show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();

                        AlertDialog.Builder build= new AlertDialog.Builder(RegisterActivity.this);
                        build.setMessage("JSON Failed")
                                .setNegativeButton("Retry",null)
                                .create()
                                .show();
                    }
                }
            };

            RegisterRequest registerRequest = new RegisterRequest(name,username,password,email,contact,age,responseListener);
            RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
            queue.add(registerRequest);
        }
    });
}
}

这是 RegistryRequest.java

public class RegisterRequest extends StringRequest{

private static final String REGISTER_REQUEST_URL="https://smplycode.000webhostapp.com/Registerft.php";
private Map<String, String> params;


public RegisterRequest(String name,String username,String password,String email,int contact, int age, Response.Listener<String> listener) {
    super(Method.POST, REGISTER_REQUEST_URL, listener, null);
    params = new HashMap<>();
    params.put("name",name);
    params.put("username",username);
    params.put("password",password);
    params.put("email",email);
    params.put("contact",contact+"");
    params.put("age",age+"");
    }

@Override
public Map<String, String> getParams() {return params;}
    }

这是我的 registerft.php 文件

<?php
    $con = mysqli_connect("localhost", "id20401_mydbname", "mydbpaord", "id2041_mydme");

    $name = $_POST["name"];
    $username = $_POST["username"];
    $password = $_POST["password"];
    $email = $_POST["email"];
    $contact = $_POST["contact"];
    $age = $_POST["age"];

    $statement = mysqli_prepare($con, "INSERT INTO usersft (name, username, password, email, contact, age) VALUES (?, ?, ?, ?, ?, ?)");
    mysqli_stmt_bind_param($statement, "ssssii", $name, $username,$password,$email,$contact, $age);
    mysqli_stmt_execute($statement);

    $response = array();
    $response["success"] = true;  

    echo json_encode($response);
?>

我在 youtube 上观看了 this 教程,这段代码正在处理该教程。

Getting this when printing response string as an alert

如果有人想提供帮助,请给我您的电子邮件 ID 我正在做一个项目我想为新手制作一个关于 C++ 学习的应用程序:)

【问题讨论】:

  • 服务器响应是什么?
  • 最重要的部分是知道你试图解析的 JSON 文本,那么如何弄清楚它是什么,正如@an_droid_dev 所说,并展示给我们。或者,也许一旦你看到它,你就会亲眼看到哪里出了问题,而这个问题是没有实际意义的。
  • 请告诉我在哪里可以看到我正在使用 000.webhost.com 进行托管
  • 查看答案我收到此错误(详细)
  • i.stack.imgur.com/naT1E.png 这是我打印响应字符串时得到的结果

标签: java php android sql json


【解决方案1】:

我会先尝试收集不同的答案和cmets

如果您在应用程序之外在RegistryRequest.java 中进行POST-Call(例如使用curl -i -X POST --data "name=name&amp;username=username&amp;password=password&amp;email=email&amp;contact=123456789&amp;age=21" https://smplycode.000webhostapp.com/Registerft.php),您会得到一个带有错误消息的HTML 页面(由其他人发布):

<br />
<b>Warning</b>:  mysqli_stmt_bind_param() expects parameter 1 to be mysqli_stmt, boolean given in <b>/storage/ssd1/901/2049901/public_html/Registerft.php</b> on line <b>12</b><br />
<br />
<b>Warning</b>:  mysqli_stmt_execute() expects parameter 1 to be mysqli_stmt, boolean given in <b>/storage/ssd1/901/2049901/public_html/Registerft.php</b> on line <b>13</b><br />

解释因为 JSON 在第一个 HTML 标记 (&lt;br /&gt;) 失败 - 这就是错误消息的内容。

现在让我们尝试分析 php错误信息,即找出根本原因:

创建数据库连接或构建语句失败并返回一个布尔值false,它不是准备好的语句 - 因此mysqli_stmt_bind_param() 上的错误。详情请见mysqli_fetch_array()/mysqli_fetch_assoc()/mysqli_fetch_row() expects parameter 1 to be resource or mysqli_result, boolean given

请确保您的 db 查询有效并且您的 php 页面返回 有效的 JSON

【讨论】:

    【解决方案2】:

    首先打印出JSONObject jsonResponse= new JSONObject(response); 之前的字符串,这样你就知道它的格式是否正确。 Br 是用于换行的 html 标记,因此我认为您的响应是 HTML 而不是 JSON

    【讨论】:

    • 检查我在打印响应字符串时得到的其他答案
    • @SumitYadav 该字符串中有 html 警告,会弄乱 JSON。您不能期望将包含 html 的字符串解析为 json。你要么需要编写一个解析器来摆脱 html,要么找到一种方法来配置你的应用程序以不发送警告
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    • 2021-11-16
    相关资源
    最近更新 更多