如何正确获取JSONARRAY项目



我有一个php文件,我从数据库检索数据,然后将其转换为数组,然后对其进行编码,因此我正在开发的Android应用程序将其jsonarray parse parse,并获取数据。

这是PHP文件:

<?php
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
$dbh = $db->connect(); // here you get the connection
$query = "SELECT *FROM lost_pets";
$result = $dbh->prepare($query);
$result->execute();
if ($result->fetchAll() > 0) {
     foreach($dbh->query($query) as $row){
        $pet["id"] = $row['id'];
        $pet["name"] = $row['name'];
        $pet["breed"] = $row['breed'];
        $response["pet"] = array($pet);
        echo json_encode($response);
     }
}
?>

这是结果:

{"pet":[{"id":"1","name":"Prueba","breed":"Yorkshire Terrier"}]}{"pet":[{"id":"2","name":"Prueba2","breed":"German Shepherd"}]}{"pet":[{"id":"3","name":"Prueba3","breed":"Beagle"}]}

问题是,当我在Android中检索Jonobject并做getJsonArray(),而不是给我3个数组,我只是得到上述结果。

我真的对PHP没有很好的了解,但是遵循PHP文档,我看不到我在做错什么。我非常接近完成该应用程序,这是我现在无法解决的唯一大问题,这确实使我感到沮丧。谢谢!

编辑:jsonparser

else if(method.equals("GET")){
        // request method is GET
        if (sbParams.length() != 0) {
            url += "?" + sbParams.toString();
        }
        try {
            urlObj = new URL(url);
            conn = (HttpURLConnection) urlObj.openConnection();
            conn.setDoOutput(false);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept-Charset", charset);
            conn.setConnectTimeout(15000);
            conn.connect();
            is = conn.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + 'n');
            }
            is.close();
            json = sb.toString();
            System.out.println(json.toString() + "This is the json");
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
//             try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }catch (NullPointerException ex){
            System.out.println("No internet");
        }
        return jObj;
    }
    conn.disconnect();
    return jObj;
}

您需要array_push,其中$ pet推入数组并打印该数组。使用,

<?php
 $arr=array();
 foreach($dbh->query($query) as $row){
    $pet["id"] = $row['id'];
    $pet["name"] = $row['name'];
    $pet["breed"] = $row['breed'];
    $response["pet"] = array_push($arr,$pet); 
 }
 print_r($arr);
?>

您需要对最终数组结构进行编码一次,在循环中编码最终会导致无效的JSON,因为您将具有多个串联的JSON字符串。

最简单的方法是仅选择您想要的字段:

$query = "SELECT id, name, breed FROM lost_pets";
$result = $dbh->prepare($query);
$result->execute();
echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
exit;

如果您需要petpets密钥,则可能需要一个循环,但可以立即分配行相同;无需分配各个字段。

我在我的所有应用中使用以下功能以获取PHP&amp;JSON数组。尝试这个。

public void ParseJsonArray(json){ //json is the json array you got. pass it to this function. this can get specific data from json array.
try {
        JSONArray jsonArray = json.getJSONArray("pet"); //get all data
        int count = 0;
//if you have more columns & you want to get specific columns.   
        while (count<jsonArray.length()){
            JSONObject JO = jsonArray.getJSONObject(count); //get data row by row.
            String s1 = JO.getString("id"); //get id value to string s1. 
            String s2 = JO.getString("name"); //get name to string s2. 
            String s3 = JO.getString("breed"); //get breed to string s3.            
            count++;        }
    } catch (JSONException e) {
        e.printStackTrace();  }
    }

最新更新