Android JSON解析问题:似乎将它分成2个独立的对象,只识别一个

时间:2013-03-13 08:41:44

标签: java php android sql json

它的作用: 它是一个Android应用程序,将模仿我的团队正在创建的网站apdata.info。 这是第二页,它将显示符合他们要求的搜索的airpoprts。

PHP

...

$sql = "SELECT apname,apcity,apstate,apcountry,IATA FROM airports WHERE MATCH(apname,apcity,apstate,apcountry,IATA) AGAINST (? IN BOOLEAN MODE)";
$link = connectToDB();
if($stmt = $link->prepare($sql))
{
    $stmt->bind_param('s', $search);

    if($stmt->execute())
    {
        $stmt->store_result();
        if($stmt->num_rows >= 1)
        {
            $resultSet = array();

            $stmt->bind_result($apname, $apcity, $apstate, $apcountry, $IATA);
            $search_rows = $stmt->num_rows;
            if($search_rows > 0){
            while($stmt->fetch())
            {
                $resultSet[] = array('apname' => $apname, 'apcity' => $apcity, 'apstate' => $apstate, 'apcountry' => $apcountry, 'IATA' => $IATA);
                //echo "Your search returned $search_rows results";
                //echo "<a href='/Airports/airport.php?IATA=".$IATA."'>".$apname."</a><br>";
    print(json_encode($resultSet));
...

Java:

private void fetchResults(String searchfor){
            String result = "";
            //the year data to send
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("search", searchfor));


            //http post
            try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://apdata.info/results/androidresult.php");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                entity = response.getEntity();
                is = entity.getContent();
                //System.out.println("------------looks good here");
            }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();
                //System.out.println(result);
            }catch(Exception e){
                Log.e("log_tag", "Error converting result "+e.toString());
            }

            System.out.println(result);
            //parse json data
            try{
                JSONArray jArray = new JSONArray(result);
                System.out.println();
                results = new ApResult[jArray.length()];
                for(int i=0;i<jArray.length();i++){
                    System.out.println("-----------jArray.length");
                        JSONObject json_data = jArray.getJSONObject(i);
                        results[i] = new ApResult(
                                json_data.getString("IATA"),
                                json_data.getString("apname"),
                                json_data.getString("apcity"),
                                json_data.getString("apstate"),
                                json_data.getString("apcountry")
                        );
                }
            }catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
            }
        }

结果 打印出结果字符串的结果:

03-13 07:40:06.985: I/System.out(220):  [{"apname":"Bismarck Municipal Airport","apcity":"Bismarck","apstate":"North Dakota","apcountry":"United States","IATA":"BIS"}][{"apname":"Bismarck Municipal 
Airport","apcity":"Bismarck","apstate":"North Dakota","apcountry":"United States","IATA":"BIS"},{"apname":"Hector International Airport","apcity":"Fargo","apstate":"North Dakota","apcountry":"United 
States","IATA":"FAR"}][{"apname":"Bismarck Municipal Airport","apcity":"Bismarck","apstate":"North Dakota","apcountry":"United States","IATA":"BIS"},{"apname":"Hector International 
Airport","apcity":"Fargo","apstate":"North Dakota","apcountry":"United States","IATA":"FAR"},{"apname":"Cologne Bonn Airport","apcity":"Cologne \/ Bonn","apstate":"North Rhine-Westphalia","apcountry":"Germany","IATA":"CGN"}][{"apname":"Bismarck Municipal Airport","apcity":"Bismarck","apstate":"North 
Dakota","apcountry":"United States","IATA":"BIS"},{"apname":"Hector International Airport","apcity":"Fargo","apstate":"North Dakota","apcountry":"United States","IATA":"FAR"},{"apname":"Cologne Bonn Airport","apcity":"Cologne \/ Bonn","apstate":"North Rhine-Westphalia","apcountry":"Germany","IATA":"CGN"},
{"apname":"Dusseldorf International Airport","apcity":"Dusseldorf","apstate":"North Rhine-Westphalia","apcountry":"Germany","IATA":"DUS"}]

问题是,jArray.length是= 1,即使我收到了更多。正如你可以看到我的输出形式,字符串似乎分为2个部分,第一部分  [{“apname”:“Bismarck Municipal Airport”,“apcity”:“Bismarck”,“apstate”:“North Dakota”,“apcountry”:“United States”,“IATA”:“BIS”}] 而所有其他人都被昏迷分开。

为了解决这个问题,我添加了一个修复此错误的函数:

private String fixBug(String result) {
        result = result.replace("][", ",");
            return result;
        }

但我想知道为什么它甚至发生在第一位。

1 个答案:

答案 0 :(得分:1)

你不应该为每个结果制作一个单独的json。您应该在一个json中包含所有结果。将数据保存在变量中,在while循环之外,您可以将其编码为有效的json。尝试使用http://jsonlint.com/进行验证。

现在你有

while() {
    $resultSet[] = array('apname' => $apname, 'apcity' => $apcity, 'apstate' => $apstate, 'apcountry' => $apcountry, 'IATA' => $IATA);
    print(json_encode($resultSet));
}

哪个应该是

while() {
    $resultSet[] = array('apname' => $apname, 'apcity' => $apcity, 'apstate' => $apstate, 'apcountry' => $apcountry, 'IATA' => $IATA);
}
print(json_encode($resultSet));