繁体   English   中英

如何在Java中读取此json数组

[英]how to read this json array in java

我有这个php生成的json数组:

$filtros=mysql_query("SELECT id_transporte FROM user_trans WHERE id_usuario =     '".$id_usuario ."'");
for($i=0; $i<=mysql_num_rows($filtros); $i++){  
$rs[]= mysql_fetch_array($filtros,MYSQL_ASSOC);
}
foreach($rs as $valor){
    if (is_array($valor)) {
        foreach($valor as $valor1){
            $reportes[]= mysql_query("
                SELECT * FROM transportes 
                WHERE id_transporte='".$valor1."'
                ORDER BY fecha_reporte DESC ");
                }
    }       
}
foreach($reportes as $valor){
    if($valor != false){
        for($i=0; $i<=mysql_num_rows($valor); $i++){
        $row[]= mysql_fetch_array($valor,MYSQL_ASSOC);
        }                           
    }       
}
print_r (json_encode($row));

返回:

[{"id_report":"73","id_transport":"624","txt_report":"Report0"},

{"id_report":"46","id_transport":"624","txt_report":"Report1"},false,

{"id_report":"74","id_transport":"9999","txt_report":"Report2"},

{"id_report":"52","id_transport":"9999","txt_report":"Report3"},false]

好吧,我尝试读取它,但是java只读取直到“ false” ...该数组是2个连接并打印的数组,所以我尝试这样做:

$row1=str_replace ( "false" , '{"salto":1}' , $row );
    $row1[]=false;
    print_r (json_encode($row1));

返回相同的内容,但最终以“”代替“ false”和“ false”,但java继续读取,直到现在为止,“”我将其用于读取json

if (jdata!=null && jdata.length() > 0){

JSONObject json_data = null;

try{                        

System.out.println( jdata.length() );//java there print all the array length ignoring the "false" o ""

for (int i=0; i < jdata.length(); i++){ 

reportsId[i]=jdata.getJSONObject(i).getString("id_report");
transportId[i]=jdata.getJSONObject(i).getString("id_transport");
txt_report[i]=jdata.getJSONObject(i).getString("txt_report");
System.out.println( " i= "+ i); 

}
}
}catch(Exception e3){}

所以我的问题是如何阅读此内容,或更改php上的某些行

首先,在您的PHP中,您不应使用mysql_*函数,因为它们已过时且危险。 您的代码可能容易受到SQL注入的攻击。 考虑使用PDO

您可以通过运行单个查询来消除错误值,从而使此过程更快。 您当然不需要将所有内容填充到数组中然后在其上循环。

这是我的看法:

$resp = mysql_query("SELECT t.* FROM transportes t 
    JOIN user_trans ut ON t.id_transporte=ut.id_transporte 
    WHERE ut.id_usuario='$id_usuario' 
    ORDER BY fecha_reporte DESC");

if(!$resp) {
    // handle the error!
    die(mysql_error())
}

$output = [];
while( $row = mysql_fetch_assoc($resp) ) {
    $output[] = $row;
}

print_r(json_encode($output));

这应该可以解决错误值的问题,因为错误值很可能是由于没有检查第二个查询是否存在错误。

JSON格式不正确。

"id_report":"46"之后缺少逗号

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM