java.lang.String 无法从 Android 转换为 JSONObject

Posted

技术标签:

【中文标题】java.lang.String 无法从 Android 转换为 JSONObject【英文标题】:java.lang.String cannot be converted to JSONObject from Android 【发布时间】:2017-01-31 23:51:18 【问题描述】:

我尝试开发一个可以使用 JSON Parser 将配置文件注册到网络托管的 android 应用程序。我成功创建了登录功能。但我收到此错误消息,指出数据库的返回对象不是 JSON 对象。我认为我的 php 文件是问题所在。

每当我尝试运行应用程序并单击按钮时,它都会显示配置文件已存在。我尝试与其他帖子进行比较,但都没有真正解决我的问题。

这是我的 register.java。 包com.teradata.sb186103.cbet;

 import android.content.Intent;
 import android.os.Bundle;
 import android.os.StrictMode;
 import android.support.v7.app.AppCompatActivity;
 import android.util.Log;
 import android.view.Menu;
 import android.view.MenuItem;
 import android.view.View;
 import android.widget.EditText;
 import android.widget.Toast;

 import org.apache.http.NameValuePair;
 import org.apache.http.message.BasicNameValuePair;
 import org.json.JSONObject;

 import java.util.ArrayList;
 import java.util.List;

public class RegisterActivity extends AppCompatActivity 

private JSONParser jsonParser;
private static String KEY_SUCCESS = "success";
String id;
private EditText consName;
private EditText consEmail;
private EditText password;

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


    consName = (EditText) findViewById(R.id.ETusername);
    consEmail = (EditText) findViewById(R.id.ETemail);
    password = (EditText) findViewById(R.id.ETpassword);



public void Register(View v) 
    try 

        String username = consName.getText().toString();
        String email = consEmail.getText().toString();
        String pass = password.getText().toString();

        //CHECK IF PROFILE ALREADY EXIST
        Boolean exist = CheckProfile(username, email, pass);
        if(exist==true)
            Toast.makeText(getApplicationContext(), "PROFILE ALREADY EXIST!", Toast.LENGTH_SHORT).show();
            return;
        

        Boolean register = RegisterProfile(id, username, email, pass);
        if(register==true)
            Toast.makeText(getApplicationContext(), "PROFILE HAS BEEN UPDATED", Toast.LENGTH_SHORT).show();

            Intent intent = new Intent(v.getContext(), ViewProfileActivity.class);
            startActivity(intent);
        


     catch (Exception e) 
        e.printStackTrace();
    




 /*   public void Cancel(View v) 

    Intent intent = new Intent(v.getContext(), MenuActivity.class);
    startActivity(intent);

   */

  public boolean CheckProfile(String consEmail, String consName, String password) throws Exception
     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    String URL = JSONParser.serverURL;
    String tag = "CheckProfile";

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

    String value = consEmail + "<@>" + consName + "<@>" + password;
    params.add(new BasicNameValuePair("tag", tag));
    params.add(new BasicNameValuePair("value", value));

    JSONObject json = jsonParser.getJSONFromUrl(URL, params);

    if (json != null && json.getString(KEY_SUCCESS) != null)
        return true;
    else return false;





public boolean RegisterProfile(String id, String consName, String consEmail, String password) throws Exception
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    String URL = JSONParser.serverURL;
    String tag = "RegisterProfile";

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

    String value = id + "<@>" + consName + "<@>" + consEmail + "<@>" + password;
    params.add(new BasicNameValuePair("tag", tag));
    params.add(new BasicNameValuePair("value", value));

    JSONObject json = jsonParser.getJSONFromUrl(URL, params);

    String res = json.getString(KEY_SUCCESS);
    if (Integer.parseInt(res) == 1)
        return true;
    
    else 
        return false;
    



@Override
public boolean onCreateOptionsMenu(Menu menu) 
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;


@Override
public boolean onOptionsItemSelected(MenuItem item) 
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) 
        return true;
    

    return super.onOptionsItemSelected(item);
   

这是我的 index.php 用于 register.java 的部分是 //Check Profile 和 //Register Profile

  <?php

  require_once ('database.php');
  date_default_timezone_set('Asia/Kuala_Lumpur'); 

   if (isset($_POST['tag']) && $_POST['tag'] != '') 

$tag = $_POST['tag'];  
$response = array("tag" => $tag, "success" => 0); 

//LOGIN
if ($tag == 'consumerLogin') 
    $value = $_POST['value'];
    $array = explode("<@>", $value);
    $consEmail = $array[0];
    $password = $array[1];

    $query = "select * from consumer where consEmail='$consEmail' and password='$password'";    
    $result = mysql_query($query);
    $row = mysql_fetch_array($result);
    if($row[0] != null)
        $response["success"] = 1;
    else
        $response["success"] = 0;
    echo json_encode($response);
    return;         



//GET ROW ID
else if ($tag == 'getID') 
    $value = $_POST['value'];
    $array = explode("<@>", $value);
    $table = $array[0];
    $column = $array[1];
    $val = $array[2];       

    $query = "select id from $table where $column = '$val'";    
    $result = mysql_query($query);
    $row = mysql_fetch_array($result);
    if($row[0] != null) 
        $response["value"] = $row[0];
        $response["success"] = 1;
    
    else 
        $response["success"] = 0;
    
    echo json_encode($response);
    return;         




//CHECK PROFILE
else if ($tag == 'CheckProfile') 
    $value = $_POST['value'];
    $array = explode("<@>", $value);
    $id= $array[0];
    $consName = $array[1];
    $consEmail = $array[2];
    $password = $array[3];                  


    $query = "select * from consumer where consName=$consName and consEmail='$consEmail' and password=$password" and id <> $id";
    $result = mysql_query($query);  
    $row = mysql_fetch_array($result);  
    $found=false;
    if($row[0]!=null)
        $found=true;

    if($found==true)           
        $response["success"] = 1;
    
    else 
        $response["success"] = 0;
    

    echo json_encode($response);
    return;     



//REGISTER PROFILE
else if ($tag == 'RegisterProfile') 
    $value = $_POST['value'];
    $array = explode("<@>", $value);
    $id= $array[0];
    $consName = $array[1];
    $consEmail = $array[2];
    $password = $array[3];                  



    $query = "insert into consumer values(null,$consName,$consEmail,'$password')";
    $result = mysql_query($query);  

    $response["success"] = 1;                       
    echo json_encode($response);
    return;     



else 
    echo "Error Message: Invalid Request";      
   

 else 
     echo "Error Message: Anynomous Access Denied"; 

 



 ?>

这是我的 JSONParser

 package com.teradata.sb186103.cbet;



  import java.io.IOException;
  import android.util.Log;
  import org.apache.http.HttpEntity;
  import org.apache.http.HttpResponse;
  import org.apache.http.NameValuePair;
  import org.apache.http.client.ClientProtocolException;
  import org.apache.http.client.entity.UrlEncodedFormEntity;
  import org.apache.http.client.methods.HttpPost;



  import org.apache.http.impl.client.DefaultHttpClient;
  import org.json.JSONException;
   import org.json.JSONObject;

     import java.io.BufferedReader;
  import java.io.InputStream;
    import java.io.InputStreamReader;
      import java.io.UnsupportedEncodingException;
    import java.util.List;

  public class JSONParser 

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
static String serverURL = "http://tdcbet.******/index.php";

public JSONParser() 



public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) 


    try 

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

     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();
        Log.e("JSON", json);
     catch (Exception e) 
        Log.e("Buffer Error", "Error converting result " + e.toString());
    


    try 
        jObj = new JSONObject(json);
     catch (JSONException e) 
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    


    return jObj;



  

日志猫

  09-23 07:32:04.923 4311-4311/com.teradata.sb186103.cbet E/JSON Parser: Error parsing data org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject
  09-23 07:32:06.935 4311-4517/com.teradata.sb186103.cbet E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb4055100
  09-23 07:32:08.580 4311-4311/com.teradata.sb186103.cbet E/JSON: <br><table border='1' cellpadding='2' bgcolor='#FFFFDF' bordercolor='#E8B900' align='center'><tr><td><font face='Arial' size='1' color='#000000'>
        <b>PHP Error Message</b></font></td></tr></table><br /><b>Warning</b>:  mysql_fetch_array(): supplied argument is not a valid MySQL result resource in <b>/home/a6410240/public_html/index.php</b> on line 
        <b>65</b><br /><br><table border='1' cellpadding='2' bgcolor='#FFFFDF' bordercolor='#E8B900' align='center'><tr><td><div align='center'>
        <a href='http://www.000webhost.com/'><font face='Arial' size='1' color='#000000'>Free Web Hosting</font></a></div></td></tr>
   </table>"tag":"CheckProfile","success":0<!-- Hosting24 Analytics Code --> 
       <script type="text/javascript" src="http://stats.hosting24.com/count.php"></script><!-- End Of Analytics Code -->
  09-23 07:32:08.580 4311-4311/com.teradata.sb186103.cbet E/JSON Parser: Error parsing data org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject
  09-23 07:32:10.586 4311-4517/com.teradata.sb186103.cbet E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb4055170
  09-23 07:32:12.177 4311-4517/com.teradata.sb186103.cbet E/Surface: getSlotFromBufferLocked: unknown buffer: 0xa2d182a0
  09-26 01:31:21.886 2906-2906/com.teradata.sb186103.cbet E/JSON Parser: Error parsing data org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject
  09-26 01:31:21.886 2906-2906/com.teradata.sb186103.cbet W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference
 09-26 01:31:21.886 2906-2906/com.teradata.sb186103.cbet W/System.err:     at com.teradata.sb186103.cbet.RegisterActivity.RegisterProfile(RegisterActivity.java:120)
 09-26 01:31:21.886 2906-2906/com.teradata.sb186103.cbet W/System.err:     at com.teradata.sb186103.cbet.RegisterActivity.Register(RegisterActivity.java:57)
 09-26 01:31:21.886 2906-2906/com.teradata.sb186103.cbet W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
 09-26 01:31:21.886 2906-2906/com.teradata.sb186103.cbet W/System.err:     at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
 09-26 01:31:21.886 2906-2906/com.teradata.sb186103.cbet W/System.err:     at android.view.View.performClick(View.java:5198)
 09-26 01:31:21.887 2906-2906/com.teradata.sb186103.cbet W/System.err:     at android.view.View$PerformClick.run(View.java:21147)
 09-26 01:31:21.887 2906-2906/com.teradata.sb186103.cbet W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
 09-26 01:31:21.887 2906-2906/com.teradata.sb186103.cbet W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
 09-26 01:31:21.887 2906-2906/com.teradata.sb186103.cbet W/System.err:     at android.os.Looper.loop(Looper.java:148)
 09-26 01:31:21.887 2906-2906/com.teradata.sb186103.cbet W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
 09-26 01:31:21.887 2906-2906/com.teradata.sb186103.cbet W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
 09-26 01:31:21.887 2906-2906/com.teradata.sb186103.cbet W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
  09-26 01:31:21.887 2906-2906/com.teradata.sb186103.cbet W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 09-26 01:31:21.887 2906-2906/com.teradata.sb186103.cbet I/Choreographer: Skipped 71 frames!  The application may be doing too much work on its main thread.
 09-26 01:37:11.337 2906-2912/com.teradata.sb186103.cbet W/art: Suspending all threads took: 13.723ms

【问题讨论】:

生成的 JSON 是什么? 显示您的 JSON 响应 我已经粘贴了我的 JSON 解析器文件@Aspicas 【参考方案1】:

在您的 PHP 代码中,您有以下几行,

else 
    echo "Error Message: Invalid Request";      
   

 else 
     echo "Error Message: Anynomous Access Denied"; 
 
 echo "masuk";

如果发生错误,此代码将正常工作。

您正试图在您的 Android 代码中将此 String 解析为 JSONObject

编辑

CheckProfile 的情况下,value 变量中有 3 个值。

String value = consEmail + "<@>" + consName + "<@>" + password;

在您的 PHP 中,您采用 4 个值。索引 3 处没有值。此外,您没有传递 id 变量。

$value = $_POST['value'];
$array = explode("<@>", $value);
$id= $array[0];
$consName = $array[1];
$consEmail = $array[2];
$password = $array[3];                  

在 PHP 中试试这个CheckProfile

$consEmail= $array[0];
$consName = $array[1];
$password = $array[2];

$query = "select * from consumer where consEmail='$consEmail'";

【讨论】:

是的,为什么会发生错误,似乎我的 php 和 sql 查询前注册有问题,我不知道在哪里修复。 @k-neeraj-lal 在我的 php 文件中 (//CHECK PROFILE & // REGISTER PROFILE @k-neeraj-lal 我已经粘贴了我的 logcat 并在您编辑时更改了我的 php 文件。尽管如此,在 logcat 中,"tag":"CheckProfile","success":0 表示它失败了。在我的数据库表中,我得到了 [id, consName, consEmail, password] @k-neeraj-lal mysql_fetch_array(): 提供的参数不是有效的 MySQL 结果资源 检查为什么会这样? 我尝试编辑我的 php 代码,因为我在行的第一列有一个 id 属性,现在我收到此错误 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang .String org.json.JSONObject.getString(java.lang.String)',我已经在上面的代码中更新了@k-neeraj-lal

以上是关于java.lang.String 无法从 Android 转换为 JSONObject的主要内容,如果未能解决你的问题,请参考以下文章

Spring @PreAuthorize hasAuthority 异常无法从类型 [java.lang.String] 转换为类型 [java.lang.Boolean] 的值'hasAuthori

无法从 VALUE_STRING 令牌中反序列化 java.lang.String[] 的实例

java.lang.String 无法从 Android 转换为 JSONObject

Spring Cloud @SqsListener MessageConversionException:无法从 [java.lang.String] 转换为 GenericMessage

java.lang.ClassCastException:java.lang.String 无法转换为

无法读取文档:无法从 START_OBJECT 令牌中反序列化 java.lang.String 的实例