无法在Android中将java.lang.String类型的值转换为JSONArray(repost)

无法在Android中将java.lang.String类型的值转换为JSONArray(repost),java,android,database,json,Java,Android,Database,Json,我重新发布这个,因为我没有找到解决这个问题的方法 这是一个错误 org.json.JSONException:Value <!DOCTYPE of type java.lang.String cannot be converted to JSONArray 以下是课程代码: entpackage com.example.blood; import java.io.BufferedReader; import java.io.InputStream; import java.io.Inp

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

这是一个错误

org.json.JSONException:Value <!DOCTYPE of type java.lang.String cannot be converted to JSONArray
以下是课程代码:

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

}
entpackage com.example.blood;
导入java.io.BufferedReader;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.json.JSONArray;
导入org.json.JSONObject;
导入android.os.Bundle;
导入android.os.StrictMode;
导入android.annotation.SuppressLint;
导入android.app.Activity;
导入android.util.Log;
导入android.view.Menu;
导入android.widget.TextView;
导入android.widget.Toast;
@SuppressLint(“新API”)
公共类MainActivity扩展了活动{
文本视图结果视图;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.enableDefaults();
resultView=(TextView)findViewById(R.id.result);
getData();
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(R.menu.main,menu);
返回true;
}
public void getData()
{
字符串结果=”;
InputStream isr=null;
试一试{
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“http://10.0.2.2/blood/index.php");
setHeader(“内容类型”、“应用程序/json”);
setHeader(“接受”、“JSON”);
HttpResponse response=httpclient.execute(httppost);
HttpEntity=response.getEntity();
isr=entity.getContent();
}捕获(例外e){
字符串err=e.toString();
resultView.setText(“无法连接到数据库”+错误);
Log.e(“错误”,err);
}
试一试{
BufferedReader读取器=新的BufferedReader(新的InputStreamReader(isr,“iso-8859-1”),8);
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
isr.close();
结果=sb.toString();
}捕获(例外e){
字符串err2=e.toString();
resultView.setText(“错误转换结果”+err2);
Log.e(“错误”,err2);
}
试一试{
字符串s=“”;
JSONArray jArray=新JSONArray(结果);

对于(int i=0;i,您的问题不在JSON中,也不在JSONArray中,因此如果出现此异常,则这意味着JSONArray的字符串与您预期的不一样。 打印该行“JSONArray jArray=new-JSONArray(result);”之前的字符串结果和字符串长度。您可以使用下面的打印消息进行打印 Log.d(“我的字符串”,“字符串结果:[“+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+

异常消息和给定的Json字符串不匹配。发布实际的Json字符串。我使用您的代码和工作字符串str=“[{\'name\':\'Muhaimin\',\'address\':\'Sylhet\',\'bgroups\':\'o+\'}];尝试{JSONArray Json=new JSONArray(str);Log.d(标记,“Json值:”);Log.d(标记,“Json值:”):+json.getJSONObject(0.getString(“bgroup”);}catch(JSONException e){//TODO自动生成的catch块e.printStackTrace();}但是如何获取[{“name\”:“Muhaimin\,“address\”:“Sylhet\,“bgroup\”:“o+\”]使用phpIf的此类型json字符串json与此示例代码中的json类似,它可以正常工作,但它与到达此行的结果JSONArray jArray=new JSONArray(结果)不符合您的预期。请直接在此行前打印结果。现在显示此错误'02-10 05:39:44.850:D/My string(889):未找到02-10 05:39:44.850:D/My String(889):02-10 05:39:44.850:D/My String(889):未找到02-10 05:39:44.850:D/My String(889):
HTTP错误404。未找到请求的资源。

02-10 05:39:44.850:D/My String(889):02-10 05:39:44.850:D/My String(889):]它的长度是:309'很好,现在我们知道你得到了这个异常。你得到它是因为当你对代码中提到的URL发出post请求时,请求失败并返回404。你需要进行以下操作:1-首先检查http post方法的返回状态并处理失败的情况。你可以使用这些方法来完成此操作response.getStatusLine().getStatusCode()response.getStatusLine().GetReasonPhase()HttpStatus.SC_确定与之比较2-您需要检查您的环境,以了解为什么无法访问此url,以及它是否为post或get方法。我在代码日志中尝试了此方法。d(“我的字符串”,“字符串结果:[“+结果+”),其长度为:“+结果.长度();但它并没有打印输出,有人能告诉我为什么吗?在我试图将结果放入它时,在创建之后,我似乎有一个JSON对象错误。
  <?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);
 ?>
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();
    }