java Android,尝试为android解析json数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6573994/
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-10-30 16:26:51  来源:igfitidea点击:

Android,trying to parse json data for android

javaandroidjson

提问by firco

I am trying to read a database in my from a remote DB, for that i am using a php code to connect to my Mysql DB and to query my DB:

我正在尝试从远程数据库读取我的数据库,为此我使用 php 代码连接到我的 Mysql 数据库并查询我的数据库:

Name of the file: check.php:

文件名:check.php:

<?php
    require_once("php/dbconnect.php");
    $query = "SELECT name FROM user ";
    $result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());

    while ( $row = mysql_fetch_array( $result ) ) {
        $output[]=$row['name'];
    }

    print(json_encode($output));
    mysql_close();
 ?/>

And the Java (Android) code to connect to the remote DB:

以及连接到远程数据库的 Java (Android) 代码:

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.Toast;
import java.net.URI;

public class ConnectToMyDb extends Activity {
    InputStream is;
    private HttpPost httppost;

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

        //http post
        try{
            HttpClient httpclient = new DefaultHttpClient();
            httppost = new HttpPost("http://www.Myurl.com/check.php");

            HttpResponse response = httpclient.execute(httppost); 
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            Log.e("log_tag", "connection success ");
            Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
        }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
            Toast.makeText(getApplicationContext(), "fail", Toast.LENGTH_SHORT).show();

        }

        //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");
                    Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
        }

        is.close();

        result=sb.toString();
    }catch(Exception e){
        Log.e("log_tag", "Error converting result "+e.toString());
        Toast.makeText(getApplicationContext(), "fail", Toast.LENGTH_SHORT).show();
    }

    //parse json data
    try{
        //ArrayList<Messages> result1 = new ArrayList<Messages>();
        JSONArray jArray = new JSONArray(result);
        JSONObject json_data= new JSONObject(result);

        for(int i=0;i<jArray.length();i++){
            json_data = jArray.getJSONObject(i);

            Log.i("log_tag"," name: "+json_data.getString("name");
                    Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
        }
    }catch(JSONException e){
        Log.e("log_tag", "Error parsing data "+e.toString());
        Toast.makeText(getApplicationContext(), "fail", Toast.LENGTH_SHORT).show();
    }
}

My problem its not the connection but the parsing of the json i get an exception:

我的问题不是连接而是解析 json 我得到一个异常:

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

采纳答案by nickfox

I would get rid of this line:

我会摆脱这一行:

JSONArray jArray = new JSONArray(result);

and do this instead:

而是这样做:

JSONObject json_data = new JSONObject(result);
JSONArray nameArray = json_data.names();
JSONArray valArray = json.toJSONArray(nameArray);

I believe this is correct, nonetheless, please study this tutorial, it will work for you:

我相信这是正确的,尽管如此,请学习本教程,它会对您有用:

Android as a Restful Client

Android 作为 Restful 客户端

回答by NT3RP

It looks like the string that you are trying to convert to JSON (i.e. result) is actually a full HTTP response. In order for your code to pass, you'll need just the raw JSON, excluding the HTML.

看起来您尝试转换为 JSON(即result)的字符串实际上是完整的 HTTP 响应。为了让您的代码通过,您只需要原始 JSON,不包括 HTML。