簡體   English   中英

Json從php腳本解析

[英]Json parsing from a php script

我正在開發一個可以訪問php腳本並解析php代碼返回的結果的android應用程序。 代碼php連接到基礎並返回結果。 問題是我得到一個錯誤:解析數據org.json.JSONException:值時出錯

感謝您的幫助:) Java代碼:

 public class ville extends Activity {
    TextView txt;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        LinearLayout rootLayout = new LinearLayout(getApplicationContext());  
        txt = new TextView(getApplicationContext());  
        rootLayout.addView(txt);  
        setContentView(rootLayout);  

        // Définir le texte et appeler la fonction de connexion.  
        txt.setText("Connexion..."); 
        // Appeler la méthode pour récupérer les données JSON
        txt.setText(getServerData(strURL)); 
    }

    // Mettre l'adresse du script PHP
    // Attention localhost ou 127.0.0.1 ne fonctionnent pas. Mettre l'adresse IP local.
    public static final String strURL = "http://192.168.1.2/www/nouveaudossier/ville.php";

    private String getServerData(String returnString) {
        InputStream is = null;
        String result = "";
        // Envoyer la requête au script PHP.
        // Script PHP : $sql=mysql_query("select * from tblVille where Nom_ville like '".$_REQUEST['ville']."%'");
        // $_REQUEST['ville'] sera remplacé par L dans notre exemple.
        // Ce qui veut dire que la requête enverra les villes commençant par la lettre L
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("Nom_ville","L"));

        // Envoie de la commande http
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(strURL);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        }catch(Exception e){
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        // Convertion de la requête en 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();
        }catch(Exception e){
            Log.e("log_tag", "Error converting result " + e.toString());
        }
        // Parse les données JSON
        try{
            JSONArray jArray = new JSONArray(result);

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

                                 // Affichage ID_ville et Nom_ville dans le LogCat

                                Log.i("log_tag","ID_ville: "+json_data.getInt("ID_ville")+

                                         ", Nom_ville: "+json_data.getString("Nom_ville")

                                 );

                                 // Résultats de la requête

                                 returnString += "\n\t" + jArray.getJSONObject(i);

                             }

                         }catch(JSONException e){

                             Log.e("log_tag", "Error parsing data " + e.toString());

                         }

                         return returnString;

                     }

                 }

PHP代碼:

<?php
  mysql_connect("localhost","root","password");
  mysql_select_db("bdVille");
  $sql=mysql_query("select * from tblVille where Nom_ville like '".$_REQUEST['ville']."%'");
  while($row=mysql_fetch_assoc($sql))
  $output[]=$row;
  print(json_encode($output));
  mysql_close();
?>

好的,可能您缺少php腳本中的內容類型標頭,請將以下行添加到php腳本中。

header('Content-type: application/json');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM