【问题标题】:Can't find the JSON parsing error that the logcat is complaining about找不到 logcat 抱怨的 JSON 解析错误
【发布时间】:2011-06-11 18:07:50
【问题描述】:

我正在尝试从 MySQL 数据库获取数据到 android 的教程,您可以在此处找到: http://www.helloandroid.com/tutorials/connecting-mysql-database

所以这是我试图从中获取数据的表:

CREATE  TABLE IF NOT EXISTS `pfc_db`.`capas` (
  `id` VARCHAR(10) NOT NULL ,
  `nombre` VARCHAR(50) NOT NULL ,
  PRIMARY KEY (`id`) )
ENGINE = InnoDB;

这是执行查询的 php 脚本片段:

$query = "select * from CAPAS";

$sql=mysql_query($query);
if (!$sql) {
    die("The query ($query) could not be executed in the BD: " . mysql_error());
}
while( $row=mysql_fetch_array($sql)){
    $output[]=$row;
    if (isset($output)){
        echo "yes ";
            echo $output[0]['nombre'];
    }
    else{echo "no";}
}
print(json_encode($output));
mysql_close();

它在浏览器上完美运行。 这是安卓代码:

package com.example.androidconn;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;

public class AndroidConnection extends Activity {
    /** Called when the activity is first created. */
    TextView txt;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // Create a crude view - this should really be set via the layout resources  
        // but since its an example saves declaring them in the XML.  
        LinearLayout rootLayout = new LinearLayout(getApplicationContext());  
        txt = new TextView(getApplicationContext());  
        rootLayout.addView(txt);  
        setContentView(rootLayout);  

        // Set the text and call the connect function.  
        txt.setText("Connecting..."); 
        //call the method to run the data retreival
        txt.setText(getServerData(KEY_121)); 
    }

    public static final String KEY_121 = "http://10.0.2.2/api/prueba.php"; //i use my real ip here

    private String getServerData(String returnString) {

        InputStream is = null;

        String result = "";
        //the year data to send
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("nombre","Escuelas"));

        //http post
        try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(KEY_121);
                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());
        }

        //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","id: "+json_data.getString("id")+
                                ", nombre: "+json_data.getString("nombre")
                        );
                        //Get an output to the screen
                        returnString += "\n\t" + jArray.getJSONObject(i); 
                }
        }catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
        }
        return returnString; 
    }    
}

最后这是 logcat:

D/AndroidRuntime(  313): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
D/AndroidRuntime(  313): CheckJNI is ON
D/AndroidRuntime(  313): --- registering native functions ---
I/ActivityManager(   58): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.example.androidconn/.AndroidConnection }
D/AndroidRuntime(  313): Shutting down VM
D/dalvikvm(  313): Debugger has detached; object registry had 1 entries
I/AndroidRuntime(  313): NOTE: attach of thread 'Binder Thread #3' failed
E/log_tag (  281): Error parsing data org.json.JSONException: Value yes of type java.lang.String cannot be converted to JSONArray
I/ActivityManager(   58): Displayed activity com.example.androidconn/.AndroidConnection: 1636 ms (total 1636 ms)

我一直在阅读教程上的cmets,所以也许有人有同样的错误但我没有找到它,这有点奇怪。

我在这里查看了类似的帖子,但它们没有帮助。如果这个问题是重复的,请指出我的答案,如果不是,任何帮助将不胜感激!

【问题讨论】:

  • 看起来result 在这一行是"yes"JSONArray jArray = new JSONArray(result);(我不应该指出)不是有效的 JSON。

标签: android mysql json parsing


【解决方案1】:

我认为您的 'echo "yes " 输出在您的 print(json_encode($output)); 输出之前被读取,然后 Android JSON 解析器会看到:

yes

它期望 JSON 的位置,因此出现错误:

java.lang.String 类型的值 yes 无法转换为 JSONArray

从您的 PHP 中删除 echo 调试语句并保留您的 while 循环:

while( $row=mysql_fetch_array($sql)){
    $output[]=$row;
}

这至少应该为您提供一些有效的 JSON 输出。

【讨论】:

  • 哇!我不知道回声会影响 json 输出。非常感谢!
  • @ferguior:echoprint 都将它们的输出发送到同一个地方。
【解决方案2】:

错误是由这一行引起的:

JSONArray jArray = new JSONArray(result);

发生这种情况是因为结果中包含的数据不代表 JSON 数组。您应该将结果中的数据打印到日志中,并查看服务器实际返回的内容。

【讨论】:

  • 这很有趣,因为现在,在@mu_is_too_short 回答之后,我得到了数据,但没有很好地解析。所以我在日志中打印了结果:try{ Log.w('testing', result); JSONArray jArray = new JSONArray(result); 但它不会在 logcat 中打印任何内容。为什么会发生这种情况?
  • 忘记了最后的评论,我有一个拼写错误。我得到的打印数据是:[{"0":"cap001","id":"cap001","1":"Escuelas","nombre":"Escuelas"}] 那不是 JSONArray 吗?那是什么?
猜你喜欢
  • 1970-01-01
  • 2022-12-28
  • 2016-07-08
  • 1970-01-01
  • 1970-01-01
  • 2010-09-12
  • 2018-10-08
  • 2020-06-22
  • 1970-01-01
相关资源
最近更新 更多