【问题标题】:Value of type java.lang.String cannot be converted to JSONArray in Android(repost)java.lang.String 类型的值无法在 Android 中转换为 JSONArray(转发)
【发布时间】:2014-02-10 10:15:30
【问题描述】:

我重新发布这个因为我没有找到解决这个问题的方法......

这里有错误

org.json.JSONException:Value <!DOCTYPE of type java.lang.String cannot be converted to JSONArray

这是 JSON 输出:

[{"name":"Muhaimin","address":"Sylhet","bgroup":"o+"}]

这是课程代码:

entpackage com.example.blood;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("NewApi")
public class MainActivity extends Activity {

TextView resultView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.enableDefaults();
resultView=(TextView) findViewById(R.id.result);
getData();
}

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

public void getData()
{
 String result="";
 InputStream isr=null;
 try{
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost=new HttpPost("http://10.0.2.2/blood/index.php");
    httppost.setHeader("Content-Type", "application/json");
     httppost.setHeader("Accept", "JSON");
    HttpResponse response=httpclient.execute(httppost);
    HttpEntity entity=response.getEntity();
    isr=entity.getContent();
  }catch(Exception e){
    String err=e.toString();
    resultView.setText("Could not connect to database"+err);
    Log.e("error", err);
  }

try{
    BufferedReader reader=new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
    StringBuilder sb=new StringBuilder();
    String line=null;
    while((line = reader.readLine()) != null){
        sb.append(line + "\n");
    }
    isr.close();

    result=sb.toString();
   }catch(Exception e){
    String err2=e.toString();
    resultView.setText("Error coverting result"+err2);
    Log.e("error", err2);
  }
  try{
    String s="";
    JSONArray jArray=new JSONArray(result);

    for(int i=0;i<jArray.length();i++){
        JSONObject json=jArray.getJSONObject(i);
        s= s + 
                "Name :"+json.getString("name")+"\n"+
                "Blood Group :"+json.getString("bgroup")+"\n" +
                "Address :"+json.getString("address")+"\n\n";
    }
    resultView.setText(s);
  }catch(Exception e){
    String err1=e.toString();
    resultView.setText("xxx"+err1);
    Log.e("error", err1);
 }
 }

}

这里是php代码:

  <?php
$con=mysql_connect("localhost","root","","BloodDB");
mysql_select_db("BloodDB",$con);

$result=mysql_query("SELECT name,address,bgroup FROM tbl_blood_donor");

while($row=mysql_fetch_assoc($result))
{
    $output[]=$row;
}
print(json_encode($output));
mysql_close($con);
 ?>

现在如何解决这个问题。我在 localhost 工作。在此先感谢

【问题讨论】:

  • 异常消息和给定的 Json 字符串不匹配。发布实际的 JSON 字符串。

标签: java android database json


【解决方案1】:

您的问题不在 JSON 中,也不在 JSONArray 中,因此如果您遇到此异常,则意味着 JSONArray 的字符串与您预期的不符。 在此行“JSONArray jArray=new JSONArray(result);”之前打印字符串结果和字符串长度。您可以为此使用以下打印消息 Log.d("My String", "string result :[" + result + "] 长度为:" + result.length());

请注意,我使用了下面的代码,它工作正常

String str = "[{\"name\":\"Muhaimin\",\"address\":\"Sylhet\",\"bgroup\":\"o+\"}]";
    try {
        JSONArray json = new JSONArray(str);
        Log.d(TAG, "Json value :" + json);
        Log.d(TAG, "Json value :" +    json.getJSONObject(0).getString("bgroup"));
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

结果: Json值:[{"bgroup":"o+","address":"Sylhet","name":"Muhaimin"}]

Json 值:o+

【讨论】:

  • 我使用你的代码和工作 String str = "[{\"name\":\"Muhaimin\",\"address\":\"Sylhet\",\"bgroup\": \"o+\"}]";尝试 { JSONArray json = new JSONArray(str); Log.d(TAG, "Json 值:" + json); Log.d(TAG, "Json 值:" + json.getJSONObject(0).getString("bgroup")); } catch (JSONException e) { // TODO 自动生成的 catch 块 e.printStackTrace();但是我怎样才能得到 [{\"name\":\"Muhaimin\",\"address\":\"Sylhet\",\"bgroup\":\"o+\"}] 这种类型的 json 字符串使用php
  • 如果 json 与此示例代码中的一样,它会起作用,但它会缝合到达这一行的结果 JSONArray jArray=new JSONArray(result) 与您预期的不一样。请直接在此行之前打印结果。
  • 现在显示这个错误 '02-10 05:39:44.850: D/My String(889): Not Found 02-10 05: 39:44.850: D/My String(889): 02-10 05:39:44.850: D/My String(889):

    Not Found

    02-10 05:39:44.850: D/My String(889):

    HTTP 错误 404。请求的资源未找到。

    02-10 05:39:44.850:D/我的字符串(889): 02-10 05:39:44.850:D/我的字符串(889): ] 并且它的长度是 :309 '
  • 很好,现在我们知道您遇到了这个异常。你得到它是因为当你向代码中提到的 URL 发出 post 请求时,请求失败并返回 404。你需要做以下事情: 1-首先检查你的 http post 方法的返回状态并处理失败的情况。您可以将这些方法用于该 response.getStatusLine().getStatusCode() response.getStatusLine().getReasonPhrase() HttpStatus.SC_OK 与它进行比较 2-您需要检查您的环境以了解为什么您无法访问此 url @987654321 @ 如果是 post 或 get 方法
  • 我在我的代码 Log.d("My String", "string result :[" + result + "] 中尝试了这个,它的长度是 :" + result.length());但它没有打印输出,谁能告诉我为什么?在我尝试将结果放入其中时,我似乎在创建之后出现了 JSON 对象错误。
猜你喜欢
  • 1970-01-01
  • 2016-02-21
  • 2013-04-03
  • 1970-01-01
  • 2018-04-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多