如何修复“解析数据 org.json.JSONException 时出错:值 <?类型为 java.lang.String 的 xml 无法转换为 JSONArray”在我的程序中

发布于 2024-12-04 04:05:08 字数 4638 浏览 0 评论 0 原文

我对android很陌生,我正在尝试制作一个程序来显示我拥有的数据库的结果。因此,当我输入名字时,数据库就会将该人的信息发送给我。然而,当我查看 LogCat 时,它说 “09-09 22:05:39.544:错误/log_tag(8813):解析数据org.json.JSONException时出错:值

这是我的代码:

public class PS extends Activity {
/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //get the two controls we created earlier, also with the resource reference and the id

    final EditText et_Text = (EditText)findViewById(R.id.et_Text);

    //add new KeyListener Callback (to record key input)
    et_Text.setOnKeyListener(new OnKeyListener()
    {
        //function to invoke when a key is pressed
        public boolean onKey(View v, int keyCode, KeyEvent event)
        {
            //check if there is 
            if (event.getAction() == KeyEvent.ACTION_DOWN)
            {
                //check if the right key was pressed
                if (keyCode == KeyEvent.KEYCODE_ENTER)
                {
                    InputStream is = null;
                    String result = "";


                    //the name data to send
                    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                    nameValuePairs.add(new BasicNameValuePair("name",et_Text.getText().toString()));

                    //http post

                    try{
                            HttpClient httpclient = new DefaultHttpClient();
                            HttpPost httppost = new HttpPost("http://myIPaddress/sampleDB/testSend.php");
                            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                            HttpResponse response = httpclient.execute(httppost);
                            HttpEntity entity = response.getEntity();
                            is = entity.getContent();
                    }catch(Exception e){
                            Log.e("log_tag", "Error in http connection "+e.toString());
                    }

                // At this point is should be set, if it isn't, tell user what went wrong
                    if (is != null) {

                    //convert response to string
                    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();

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

                    //parse json data
                    try{
                            JSONArray jArray = new JSONArray(result);
                            for(int i=0;i<jArray.length();i++){
                                    JSONObject json_data = jArray.getJSONObject(i);
                                    Log.i("log_tag","PersonID: "+json_data.getInt("personID")+
                                            ", FirstName: "+json_data.getString("FirstName")+
                                            ", LastName: "+json_data.getString("LastName")+
                                            ", Age: "+json_data.getInt("Age")
                                    );

                    } 

                    }catch(JSONException e){
                            Log.e("log_tag", "Error parsing data "+e.toString());

                    }} else {Log.i("log_tag", "Something went wrong!"//I don't know what to put here);} ;  




                  et_Text.setText("");                            
                                    //and clear the EditText control
                return true;
                } 


                }

            return false;
        }
    }); 

}
}

这是我的 php 代码:

<?php
$con = mysql_connect("localhost","username","password");
if (!$con)
  {
   die('Could not connect: ' . mysql_error());
   }

 mysql_select_db("_usersDB", $con);

 $q=mysql_query("SELECT * FROM Persons WHERE FirstName='".$_REQUEST['name']."'");
 while($e=mysql_fetch_assoc($q))
    $output[]=$e;

 print(json_encode($output));

 mysql_close($con);
 ?>

它解析的输出是当我输入“Eric”时,它会给我 personID 1、FirstName of Eric、LastName of(我的姓氏)和年龄 15。我不确定你是否有这样的要求......

I am very new to android and I'm trying to make a program that shows you results from a database that I have. So when I type in a first name and the database sends the information of that person to me. However, when I look at the LogCat it says
"09-09 22:05:39.544: ERROR/log_tag(8813): Error parsing data org.json.JSONException: Value

This is my code:

public class PS extends Activity {
/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //get the two controls we created earlier, also with the resource reference and the id

    final EditText et_Text = (EditText)findViewById(R.id.et_Text);

    //add new KeyListener Callback (to record key input)
    et_Text.setOnKeyListener(new OnKeyListener()
    {
        //function to invoke when a key is pressed
        public boolean onKey(View v, int keyCode, KeyEvent event)
        {
            //check if there is 
            if (event.getAction() == KeyEvent.ACTION_DOWN)
            {
                //check if the right key was pressed
                if (keyCode == KeyEvent.KEYCODE_ENTER)
                {
                    InputStream is = null;
                    String result = "";


                    //the name data to send
                    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                    nameValuePairs.add(new BasicNameValuePair("name",et_Text.getText().toString()));

                    //http post

                    try{
                            HttpClient httpclient = new DefaultHttpClient();
                            HttpPost httppost = new HttpPost("http://myIPaddress/sampleDB/testSend.php");
                            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                            HttpResponse response = httpclient.execute(httppost);
                            HttpEntity entity = response.getEntity();
                            is = entity.getContent();
                    }catch(Exception e){
                            Log.e("log_tag", "Error in http connection "+e.toString());
                    }

                // At this point is should be set, if it isn't, tell user what went wrong
                    if (is != null) {

                    //convert response to string
                    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();

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

                    //parse json data
                    try{
                            JSONArray jArray = new JSONArray(result);
                            for(int i=0;i<jArray.length();i++){
                                    JSONObject json_data = jArray.getJSONObject(i);
                                    Log.i("log_tag","PersonID: "+json_data.getInt("personID")+
                                            ", FirstName: "+json_data.getString("FirstName")+
                                            ", LastName: "+json_data.getString("LastName")+
                                            ", Age: "+json_data.getInt("Age")
                                    );

                    } 

                    }catch(JSONException e){
                            Log.e("log_tag", "Error parsing data "+e.toString());

                    }} else {Log.i("log_tag", "Something went wrong!"//I don't know what to put here);} ;  




                  et_Text.setText("");                            
                                    //and clear the EditText control
                return true;
                } 


                }

            return false;
        }
    }); 

}
}

This is my php code:

<?php
$con = mysql_connect("localhost","username","password");
if (!$con)
  {
   die('Could not connect: ' . mysql_error());
   }

 mysql_select_db("_usersDB", $con);

 $q=mysql_query("SELECT * FROM Persons WHERE FirstName='".$_REQUEST['name']."'");
 while($e=mysql_fetch_assoc($q))
    $output[]=$e;

 print(json_encode($output));

 mysql_close($con);
 ?>

The output it's parsing on is when I input "Eric" then It'll give me personID of 1, FirstName of Eric, LastName of (my last name), and age of 15. I'm not sure if you were asking for that...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

沙沙粒小 2024-12-11 04:05:08

首先,与世界其他地方共享您的数据库连接详细信息可能并不明智。其次,在 UI 线程上进行网络操作并不是一个好主意。

最后(这是您想知道的),看起来服务器上的输出可能与客户端期望的不同。您可以发布它正在解析的输出吗?一旦您这样做,我就会修改这个答案。

First of all, it may not be wise to share your database connection details with the rest of the world. Second of all, it's not a great idea to do networking operations on the UI Thread.

Lastly (which is what you want to know), it looks likes the output on the server may be different than what the client is expecting. Can you post the output it is parsing on? I'll revise this answer once you do so.

摘星┃星的人 2024-12-11 04:05:08

看起来服务器好像在 JSON () 前面添加了 XML 声明。作为第一步,您可能需要检查 Web 服务器输出的 HTTP 流量(通过日志记录或wireshark),以确定问题出在客户端还是服务器上。

It looks as if the server is prepending an XML declaration to the JSON (). You might want to examine the HTTP traffic output by the web server (via logging or wireshark) as a first step to see if the problem lies with the client or the server.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文