我知道几乎没有类似的线程,但是它们都没有真正的帮助。我正在尝试将PHP foreach循环解析为Json,然后解析为Android。有一个URL地址列表,可以在其中下载apk文件,这就是我正在浏览的内容。 这是我每次运行程序时都会遇到的错误。
Error :- org.json.JSONException: Value ["xxxx.apk"] of type org.json.JSONArray cannot be converted to JSONObject
PHP代码:
$fileList = glob('xxxx/xxx/appstore_php/*');
foreach($fileList as $filename)
{
if ( is_file ( $filename ) )
{
$bname = basename ( $filename);
$b = array($bname);
echo json_encode($b);
}
}
输出:-[“ xxxx.apk”] [“ xxy.apk”]
Android代码:
private void getAppData(){
//Creating a string request
StringRequest stringRequest = new StringRequest(URLAddress.SHOW_ALL_APK,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(URLAddress.JSON_ARRAY);
getApps(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getApps(JSONArray j){
//Traversing through all the items in the json array
for(int i=0;i<j.length();i++){
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
appList.add( json.toString() );
} catch (JSONException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
表单聊天讨论,回复返回为{"files": ["xxxx.apk","xxy.apk"]}
格式
$fileList = glob('xxxx/xxx/appstore_php/*');
$files = [];
foreach($fileList as $filename)
{
if ( is_file ( $filename ) )
{
$bname = basename ( $filename);
$files[] = $bname;
}
}
header('Content-Type: application/json');
$response = ["files" => $files]; //later you can add extra in it too
echo json_encode($response);
这里的输出应该是这样
{"files": ["xxxx.apk","xxy.apk"]}