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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21674326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:01:48  来源:igfitidea点击:

Value of type java.lang.String cannot be converted to JSONArray in Android(repost)

javaandroiddatabasejson

提问by user3279100

I am repost this coz I dont find the solution for this problem...

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

here is error

这是错误

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

here is JSON output:

这是 JSON 输出:

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

here is class code:

这是类代码:

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

}

here is php code:

这是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);
 ?>

Now how to solve this problem.I am working in localhost.thanks in advance

现在如何解决这个问题。我在 localhost 工作。提前谢谢

采纳答案by Mina Tadros

Your problem is not in JSON and not in the JSONArray so if you got this exception then this means the string to JSONArray not as you expected. Print the string result and the string length before this line "JSONArray jArray=new JSONArray(result);". You can use the below print message for that Log.d("My String", "string result :[" + result + "] and its length is :" + result.length());

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

Note that, I used the below code and it working fine

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

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

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

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

Json value :o+

JSON 值 :o+