当前位置: 首页 > 知识库问答 >
问题:

分析数据组织时出错。json。JSONException:在的字符0处输入结束

云何平
2023-03-14

我正在尝试登录应用程序,但我一直遇到“解析数据org.json.JSONException错误:在字符0的输入结束”

我的登录名。java看起来像这样

公共类登录扩展活动实现OnClickListener{私有EditText用户,pass;

private Button mSubmit, mRegister;

 // Progress Dialog
private ProgressDialog pDialog;

// JSON parser class

JSONParser jsonParser = new JSONParser();

//php login script location:

//localhost :
//testing on your device

//put your local ip instead,  on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1


//testing on Emulator:

私有静态最终字符串LOGIN_URL="my url";

//从真实服务器进行测试

//JSON element ids from repsonse of php script:

private static final String TAG_SUCCESS = "success";

private static final String TAG_MESSAGE = "message";



@Override

protected void onCreate(Bundle savedInstanceState) {

    // TODO Auto-generated method stub

   super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_login);
  //setup input fields

    user = (EditText)findViewById(R.id.username);

    pass = (EditText)findViewById(R.id.password);





    //setup buttons

    mSubmit = (Button)findViewById(R.id.button1);

    mRegister = (Button)findViewById(R.id.button2);
  //register listeners

    mSubmit.setOnClickListener(this);

    mRegister.setOnClickListener(this);

}

@Override

public void onClick(View v) {

    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.button1:
            new AttemptLogin().execute();
        break;
    case R.id.button2:
         Intent i = new Intent(this, Register.class);

            startActivity(i);
        break;

    default:
        break;
 }

}

class AttemptLogin extends AsyncTask<String, String, String> {
  /**


     * */


    boolean failure = false;


    @Override

    protected void onPreExecute() {



        super.onPreExecute();

        pDialog = new ProgressDialog(Login.this);

        pDialog.setMessage("Attempting login...");
     pDialog.setIndeterminate(false);
     pDialog.setCancelable(true);
    pDialog.show();

    }
@Override

    protected String doInBackground(String... args) {
    /** String username = user.getText().toString();


     String password = pass.getText().toString();**/

    String username,password;
     username = user.getText().toString();


     password = pass.getText().toString();



        // TODO Auto-generated method stub

         // Check for success tag

        int success;

        try {

            // Building Parameters

            List<NameValuePair> params = new ArrayList<NameValuePair>();

            params.add(new BasicNameValuePair("username", username));

            params.add(new BasicNameValuePair("password", password));

            Log.d("request!", "starting");

            // getting product details by making HTTP request

            JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);



            // check your log for json response

            Log.d("Login attempt", json.toString());



            // json success tag

            success = json.getInt(TAG_SUCCESS);



            if (success == 1) {

                Log.d("Login Successful!", json.toString());
          Intent i = new Intent(Login.this, ReadComments.class);

                finish();

                startActivity(i);

                return json.getString(TAG_MESSAGE);

            }else{

                Log.d("Login Failure!", json.getString(TAG_MESSAGE));

                return json.getString(TAG_MESSAGE);

            }




        } catch (JSONException e) {

            e.printStackTrace();

        }

        return null;

    }

    /**

     * After completing background task Dismiss the progress dialog

     * **/

    protected void onPostExecute(String file_url) {

        // dismiss the dialog once product deleted

        pDialog.dismiss();

        if (file_url != null){

            Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();

        }

    }

}

}

我的JSONParser。java如下所示:`

公共类JSONParser{

static InputStream is = null;   static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
    // Making HTTP request
    try {
        // defaultHttpClient
        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();
    }
    try {

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();

        String line = null;

        while ((line = reader.readLine()) != null) {

            sb.append(line + "\n");
        }
       is.close();

        json = sb.toString();

    } catch (Exception e) {

        Log.e("Buffer Error", "Error converting result " + e.toString());
    }
    // try parse the string to a JSON object
    try {

        jObj = new JSONObject(json);

    } catch (JSONException e) {

        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
    // return JSON String
    return jObj;
}

//函数从url获取json

//通过制作HTTP POST或GET mehtod

公共JSONObject makeHttpRequest(字符串url、字符串方法、列表参数){

   // Making HTTP request

   try {

       // check for request method

       if(method == "POST"){

           // request method is POST

           // defaultHttpClient

           DefaultHttpClient httpClient = new DefaultHttpClient();

           HttpPost httpPost = new HttpPost(url);

           httpPost.setEntity(new UrlEncodedFormEntity(params));

           HttpResponse httpResponse = httpClient.execute(httpPost);

           HttpEntity httpEntity = httpResponse.getEntity();

           is = httpEntity.getContent();





       }else if(method == "GET"){

           // request method is GET

           DefaultHttpClient httpClient = new DefaultHttpClient();

           String paramString = URLEncodedUtils.format(params, "utf-8");

           url += "?" + paramString;

           HttpGet httpGet = new HttpGet(url);

           HttpResponse httpResponse = httpClient.execute(httpGet);

           HttpEntity httpEntity = httpResponse.getEntity();

           is = httpEntity.getContent();

    }          

   } catch (UnsupportedEncodingException e) {

       e.printStackTrace();

   } catch (ClientProtocolException e) {

       e.printStackTrace();
       Log.e("Buffer Error", "ClientProtocolException " + e.toString());
   } catch (IOException e) {
       e.printStackTrace();

       Log.e("Buffer Error", "IOException " + e.toString());
   }

   try {
       BufferedReader reader = new BufferedReader(new InputStreamReader(
               is, "iso-8859-1"), 8);
       StringBuilder sb = new StringBuilder();
       String line = null;
       while ((line = reader.readLine()) != null) {

           sb.append(line + "\n");
       }
       is.close();
       json = sb.toString();


   } catch (Exception e) {
       Log.e("Buffer Error", "Error converting result " + e.toString());
   }

   // try parse the string to a JSON object
   try {

       jObj = new JSONObject(json);

   } catch (JSONException e) {

       Log.e("JSON Parser", "Error parsing data " + e.toString());

   }

   // return JSON String
   return jObj;

}}

我的登录名。php看起来像

//加载并连接到MySQL数据库,需要(“config.inc.php”);

如果(!空($_POST)) { //根据用户名获取用户信息。

$query = "

        SELECT

            id,username,password  

        FROM users  

        WHERE  

            username = :username

    ";  



$query_params = array(  

    ':username' => $_POST['username']  

);

try {  

    $stmt   = $db->prepare($query);  

    $result = $stmt->execute($query_params);  

}  

catch (PDOException $ex) {  

    // For testing, you could use a die and message.  

    //die("Failed to run query: " . $ex->getMessage());         

    //or just use this use this one to product JSON data:  

    $response["success"] = 0;  

    $response["message"] = "Database Error1. Please Try Again!";  
    // echo json_encode($response);  
   // die(json_encode($response));  
}  



//This will be the variable to determine whether or not the user's information is   correct.  

//we initialize it as false.  

$validated_info = false;  

//fetching all the rows from the query  

$row = $stmt->fetch();  

if ($row) {  

    //if we encrypted the password, we would unencrypt it here, but in our case we just  

    //compare the two passwords  

    if ($_POST['password'] === $row['password']) {  

        $login_ok = true;  

    }

}



// If the user logged in successfully, then we send them to the private members-only page  

// Otherwise, we display a login failed message and show the login form again  

if ($login_ok) {  

    $response["success"] = 1;  

    $response["message"] = "Login successful!";  
   //  echo json_encode($response);  
   // die(json_encode($response));  

} else {  

    $response["success"] = 0;  

    $response["message"] = "Invalid Credentials!";  
  //   echo json_encode($response);  
 //   die(json_encode($response))  

}   

die(json\U编码($响应))
}其他{

?

    <h1>Login</h1>

    <form action="login.php" method="post">

        Username:<br />

        <input type="text" name="username" placeholder="username" />

        <br /><br />

        Password:<br />

        <input type="password" name="password" placeholder="password" value="" />

        <br /><br />

        <input type="submit" value="Login" />

    </form>

    <a href="register.php">Register</a>

<?php

}

?

最后我的日志

'08-21 01:28:53.663:D/请求!(32513):启动
08-21 01:28:54.507:D/dalvikvm(32513):GC\u FOR\u MALLOC freed 134K,47%free 3032K/5639K,外部507K/517K,暂停101ms
08-21 01:29:04.921:E/JSON解析器(32513):错误解析数据组织。json。JSONException:08-21 01:29:04.929的字符0处输入结束:W/dalvikvm(32513):threadid=9:线程以未捕获异常退出(组=0x40018578)
08-21 01:29:04.952:E/AndroidRuntime(32513):致命异常:AsyncTask#1
08-21 01:29:04.952:E/AndroidRuntime(32513):java。lang.RuntimeException:在android上执行doInBackground()时出错。操作系统。异步任务3美元。完成(AsyncTask.java:200)
08-21 01:29:04.952:E/AndroidRuntime(32513):在java。util。同时发生的FutureTask$同步。innerSetException(FutureTask.java:274)
08-21 01:29:04.952:E/AndroidRuntime(32513):java。util。同时发生的未来任务。setException(FutureTask.java:125)
08-21 01:29:04.952:E/AndroidRuntime(32513):java。util。同时发生的FutureTask$同步。innerRun(FutureTask.java:308)
08-21 01:29:04.952:E/AndroidRuntime(32513):java。util。同时发生的未来任务。运行(FutureTask.java:138)
08-21 01:29:04.952:E/AndroidRuntime(32513):在java上运行。util。同时发生的线程池执行器。runWorker(ThreadPoolExecutor.java:1088)
08-21 01:29:04.952:E/AndroidRuntime(32513):在java。util。同时发生的ThreadPoolExecutor$工作者。运行(ThreadPoolExecutor.java:581)
08-21 01:29:04.952:E/AndroidRuntime(32513):在java上运行。lang.Thread。运行(Thread.java:1019)
08-21 01:29:04.952:E/AndroidRuntime(32513):由:java引起。lang.NullPointerException
08-21 01:29:04.952:E/AndroidRuntime(32513):位于com。实例prova1.Login$尝试登录。doInBackground(Login.java:179)08-21 01:29:04.952:E/AndroidRuntime(32513):位于com。实例prova1.Login$尝试登录。doInBackground(Login.java:1)
08-21 01:29:04.952:E/AndroidRuntime(32513):在android上。操作系统。异步任务2美元。调用(AsyncTask.java:185)
08-21 01:29:04.952:E/AndroidRuntime(32513):在java上。util。同时发生的FutureTask$同步。innerRun(FutureTask.java:306)
08-21 01:29:04.952:E/AndroidRuntime(32513):。。。4更多08-21 01:29:12.710:E/WindowManager(32513):活动com。实例验证1。登录名泄漏了窗口com.Android内部的政策实施。电话窗口$DecorView@4054add8最初添加到这里的是08-21 01:29:12.710:E/WindowManager(32513):android。看法WindowLeaked:活动com。实例验证1。登录名泄漏了窗口com.Android内部的政策实施。电话窗口$DecorView@4054add8最初添加到这里的是android上的WindowManager(32513)。看法ViewRoot。(ViewRoot.java:263)
08-21 01:29:12.710:E/WindowManager(32513):在android上。看法WindowManagerImpl。addView(WindowManagerImpl.java:171)
08-21 01:29:12.710:E/WindowManager(32513):在android上。看法WindowManagerImpl。addView(WindowManagerImpl.java:114)
08-21 01:29:12.710:E/WindowManager(32513):在android上。看法窗口$LocalWindowManager。addView(Window.java:424)
08-21 01:29:12.710:E/WindowManager(32513):在android上。应用程序。对话显示(Dialog.java:241)
08-21 01:29:12.710:E/WindowManager(32513):在com上。实例prova1.Login$尝试登录。onPreExecute(Login.java:134)
08-21 01:29:12.710:E/WindowManager(32513):在android上。操作系统。异步任务。在com上执行(AsyncTask.java:391)
08-21 01:29:12.710:E/WindowManager(32513)。实例prova1.Login。onClick(Login.java:97)
08-21 01:29:12.710:E/WindowManager(32513):在android上。看法看法performClick(View.java:2485)
08-21 01:29:12.710:E/WindowManager(32513):在android上。看法查看$PerformClick。在android上运行(View.java:9080)
08-21 01:29:12.710:E/WindowManager(32513)。操作系统。处理程序。handleCallback(Handler.java:587)
08-21 01:29:12.710:E/WindowManager(32513):在android上。操作系统。处理程序。dispatchMessage(Handler.java:92)
08-21 01:29:12.710:E/WindowManager(32513):在android上。操作系统。活套。loop(Looper.java:130)08-21 01:29:12.710:E/WindowManager(32513):在android上。应用程序。ActivityThread。main(ActivityThread.java:3687)
08-21 01:29:12.710:E/WindowManager(32513):位于java。lang.reflect。方法invokenactive(本机方法)
08-21 01:29:12.710:E/WindowManager(32513):java。lang.reflect。方法调用(Method.java:507)
08-21 01:29:12.710:E/WindowManager(32513):在com上。Android内部的操作系统。ZygoteInit$MethodandArgscaler。运行(ZygoteInit.java:867)08-21 01:29:12.710:E/WindowManager(32513):在com上。Android内部的操作系统。合子岩。main(ZygoteInit.java:625)
08-21 01:29:12.710:E/WindowManager(32513):位于dalvik。系统NativeStart。main(本机方法)`

我们将非常感谢您的帮助。。非常感谢。

共有1个答案

翁翰
2023-03-14

我看到,在PHP中,您返回一个JSONarray,在代码中,您像JSONobject一样解析它。

首先尝试将其解析为JSONarray,然后获取JSONobect

JSONArray jsonarray = new JSONArray(json);
JSONObject jsonobj = jsonarray.getJSONObject(0);
int x = jsonobj.getInt("success");
 类似资料:
  • 以下是所有的错误: 下面是我的代码:

  • 我见过其他人遇到这个问题,但没有一个帖子能够帮助我。我试图在REST调用库中使用Volley,当我试图使用带有JSON对象的Put调用作为参数时,我得到了错误:org。json。JSONException:输入结束于的字符0处。 代码如下: jsonParams日志显示: 有没有其他我错过的场景?看起来请求无法解析JSON对象。我甚至尝试创建一个HashMap,然后用它创建一个JSON对象,但仍然

  • 问题内容: 我正在尝试从服务器获取JSON值。我不知道我的代码有什么问题。我正在使用,这是我的代码在 码: 这是logcat 这是 JSON 格式 问题答案: 您可能会得到一个空白的答复。它不为null,但 jsontext 为空。因此,您将收到此错误,而不是Nullpointer异常 您是否正在向服务器发送正确的参数。还要检查url是否响应POST请求。

  • 问题内容: 解析JSON时出现错误。解析数据org.json.JSONException时出错:输入的第0个字符。 错误日志: 这是在UserFunction类中调用函数的代码: UserFunction类中的函数 Java解析器类: 这是我的index.php API index.php调用此orderdetails函数 新的JSON响应。尽管我必须要生产的产品不能显示阵列。为什么JSON标签显

  • 问题内容: 我已经看到其他人遇到了这个问题,但是没有一个帖子能够帮助我。我正在尝试将Volley用于我的REST调用库,当我尝试将JSON对象作为参数使用Put调用时,我得到了。 这是代码: jsonParams日志显示: 我还有其他设置吗?看来请求无法解析JSON对象。我什至尝试创建一个HashMap,然后使用它创建一个JSON对象,但是我仍然得到相同的结果。 问题答案: 我也遇到了这个问题。

  • 问题内容: 我正在开发一个测试Android应用程序,该应用程序必须显示mysql数据库中的一些数据。这是我的日志: 这里是JSONParser.java类 在这里,我用来显示所选数据的类: 这里的PHP文件: 另外,这里主要活动: 我在互联网上阅读了有关此错误的各种线索,但它甚至是由差异问题引起的,我没有找到与我的情况类似的情况或解决了我问题的解决方案。 问题答案: 看起来您的PHP文件正在返回