在android中使用json获取服务器上文件夹的文件列表


get list of files of a folder on server with json in android

我使用这些代码来获取服务器上文件夹的文件列表:

<?php
 if ($handle = opendir('.pic')) {
   while (false !== ($file = readdir($handle))) {
          if ($file != "." && $file != "..") {
            //$thelist = $thelist.$file.'<br>';
            $thelist = $thelist.$file."'r'n";
          }
       }
  closedir($handle);
  }
 echo $thelist;
?>

它的工作很好,但我需要得到json数组文件名,mysql我使用这些代码来获取json数组:

$result = mysql_query("SELECT *FROM wall ORDER BY id DESC") or die(mysql_error());
if (mysql_num_rows($result) > 0) {
    $response["products"] = array();
    while ($row = mysql_fetch_array($result)) {
        $product = array();
        $product["name"] = $row["name"];
        array_push($response["products"], $product);
    }
    $response["success"] = 1;
echo json_encode($response);

但我不知道如何改变它,以获得文件名与json数组就像mysql.

更新:我尝试这些代码:

<?php
 $thelist = array();
 if ($handle = opendir('.pic')) {
   while (false !== ($file = readdir($handle))) {
          if ($file != "." && $file != "..") {
            $thelist[] = $file;
          }
       }
  closedir($handle);
  }
 echo json_encode($thelist);

在android中,我尝试用这些代码获取json:

List<NameValuePair> params = new ArrayList<NameValuePair>();
            JSONObject json = jParser.getJSONFromUrl(url_all_products, params);
            Log.d("All Products: ", json.toString());

和我有这个错误在logcat:

解析数据org.json.JSONException: Value [] of type org.json.JSONArray cannot convert to JSONObject

有谁能帮我吗?

我更喜欢使用glob()从一般文件夹中获取文件(和/或文件夹)列表。

首先,你应该初始化一个数组,然后再添加到该数组。

这是我的解决方案:

<?php
$list = []; // Since 5.4.x you can use shorthand syntax to init an array
$dir = dirname(__FILE__); // Just to get the path to current dir
// glob returns an array with the files it found matching the search pattern (* = wildcard)
$files = glob($dir."/.pic/*");
// Looping through all the files found in ./.pic
foreach ($files as $file) {
    // Removing the full path and appending the file to the $list array.
    // Now it will look like ".pic/filename.ext"
    $list[] = str_replace($dir."/", "", $file); 
}
echo json_encode($list, JSON_PRETTY_PRINT); // JSON_PRETTY_PRINT for beautifying the output
?>

顺便说一下,glob()可以接受更多选项,您可以在php手册(glob)

中阅读更多关于它的信息。

建议更新nr 1这个json的输出将是一个json数组,正如错误消息所说的那样。一种解决办法是将JSONObject json改为JSONArray json

另一方面,您可以通过在代码中做一个小小的调整,使PHP脚本的输出成为json对象而不是数组。

代替echo json_encode($list, JSON_PRETTY_PRINT);,只需将$list添加到另一个数组中,像这样:
echo json_encode(['files' => $list], JSON_PRETTY_PRINT);

这将使解析器将其视为json对象,因为数组具有字符串键(files)而不是索引键(0, 1, ..., n)

创建一个文件名数组,json_encode:

<?php
 $thelist = array();
 if ($handle = opendir('.pic')) {
   while (false !== ($file = readdir($handle))) {
          if ($file != "." && $file != "..") {
            $thelist[] = $file;
          }
       }
  closedir($handle);
  }
 echo json_encode($thelist);