JSON解析:来自PHP5(攻击数据库:mySQL)ios5 iphone

I hope someone can help me put because I've trying the whole day :( ( newly stuff )

I have a database mySQL, which contains one table "products" ( two rows : "id" and "stock" ). And I want my ios5 app to send an "id" and receive the "stock" of that product.

In my PHP code:

echo json_encode(array(
     'id'=>$id,
     'stock'=>$stock, ));

Which I believe sends a JSON to my app, my app receives this JSON in a function called:

- (void)requestFinished:(ASIHTTPRequest *)request
{    
    NSString *responseStringWEB = [request responseString];
    NSLog(@"STRING:: %@ 
", responseStringWEB); //3
    NSDictionary *responseDict = [responseStringWEB JSONValue];
    NSLog(@"DICT: %@ 
", responseDict); //3
    NSString *id_producto = [responseDict objectForKey:@"id"];
    NSString *stock = [responseDict objectForKey:@"stock"];
    NSLog(@"ID: %@
", id_producto); //3
    NSLog(@"stock: %@", stock); //3
}

and checking the console I get:

**`STRING`::**
Connection establishedDatabase selected..
***{"id":"3","stock":"46"}***
Connection closedDesconectado
2011-12-26 18:58:57.170 CaeDeCajon[1998:16403] Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x984aeb0 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
2011-12-26 18:58:57.171 CaeDeCajon[1998:16403] **`DICT`**: (null)
2011-12-26 18:58:57.171 CaeDeCajon[1998:16403] **`ID`**: (null)
2011-12-26 18:58:57.171 CaeDeCajon[1998:16403] **`stock`**: (null)

The question is : I do not know what format the JSON is coming ( array, How should I parse the NSstring responseStringWEB to get those two values ( ID and STOCK ). It seems I receive them from the database but I do not reach to extract them.

HELP :) thank you ,

EDITING::

Thanks. It really Helped.

It seemed that there has had something to do with the multiple echos I used in the PHP code. Now I only have one echo, sending data in json format. It works perfectly with my database and my app: I receive the whole table ( "id" and "stock" ) of all items. Thanks.

But I have found another obstacle ( no wonder ), is that I need to change the database once the products have been sold, and as they´re not usually sold 1 by 1 must post arrays into PHP,, my intention is to POST the id and reductor(reductor represent how many products of that "id" were sold ) of the products/items affected ( array_id and array_reductor).

IOS5 CODE:

NSArray *array_id=[[NSArray alloc]initWithObjects:@"0",@"3",@"5", nil]; 

//with the id products;

NSArray *array_reductor=[[NSArray alloc]initWithObjects:@"10",@"5",@"40", nil];

//with the number of products sold ( so I have to decrease the previous stock number in the database by these to obtain the current stock numbers ).

NSURL *url=[[NSURL alloc]initWithString:@"http://www.haveyourapp.com/promos/"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:array_id forKey:@"id"];
[request setPostValue:array_reductor forKey:@"reductor"];

[request setDelegate:self];
[request startAsynchronous];

MY PHP FILE:

if (isset($_POST['id'])&&isset($_POST['reductor'])) // check if data is coming {

$id = array();          // I create arrays
$reductor = array();

$id=$_POST['id'];             // and store arrays in them ( At least is what I believe )
$reductor=$_POST['reductor'];

$connection = new createConnection(); //i created a new object
$connection->connectToDatabase(); // connected to the database
$connection->selectDatabase();

/////////////////////////////////////////////////////////////////////////////////////////////////////////////// Stock reduction in the items affected////////////////////////////////


$num=mysql_numrows($id);
$i=0;
$stock_anterior=array();
while ($i < $num) {

$query=" SELECT  stock FROM productos WHERE id = $id[$i]";
$stock_anterior[$i] = mysql_query($query);
++$i;
}


$l=0;

$num2=mysql_numrows($id);

while ($l < $num2) {

$stock_reductor[$l] = $stock_anterior[$l] - $reductor[$l];

$query = "UPDATE productos SET stock = '$stock_reductor[$l]' WHERE id = $id[$l] ";
mysql_query($query);


++$l;

}



$connection->closeConnection();

But my code is not working, I don not know if the problem is in my app or in the PHP file ( likely ), but how can I receive those two arrays and work with them????

Thanks in advance

I spend a lot of time on stack Overflow: VERY USEFULLLLLLLL!!!!!

3个回答



使用 HTTPScoop 。 基于控制台输出,我怀疑出现了问题,其中包含行 Connection establishedDatabase selected .. </ code>和 Connection closedDesconectado </ code> ... </ p>

  **STRING :: ** 
Connection establishedDatabase selected ..
*** {“id”:“3”,“stock”:“46”} ***
Connection closedDesconectado \ n </ code> </ pre>

看起来你已经从JSON启动之前打印的那个脚本中获得了一些日志记录,这在iOS端的JSON解析器上是不被接受的。 </ p>
</ div>

展开原文

原文

Check the PHP script output using a tool such as HTTPScoop. I suspect that something is wrong, based on the console output, which contains the lines Connection establishedDatabase selected.. and Connection closedDesconectado...

**`STRING`::**
Connection establishedDatabase selected..
***{"id":"3","stock":"46"}***
Connection closedDesconectado

It looks like you've got some logging from that script that is printed before the JSON starts, which isn't accepted by the JSON parser on the iOS end.

duancan8382
duancan8382 感谢Joerick,我认为你的权利,因为我删除了PHP中的所有回声工作正常。 现在的问题是从应用程序接收PHP中的数组。 任何建议?
接近 9 年之前 回复



json_encode仅适用于UTF-8编码数据,因此当找到无效字符时,它会为所有人返回NULL。</ p> \ n

检查您的数据是否以UTF-8编码。</ p>

同时检查您的文件是否使用UTF-8。</ p>

另一种选择 to json_encode:</ p>

  //funcióninterna:comprueba si un array es puro o no 
// es puro sisusíndicesson:0,1,2,... ,N
function aputio($ a){
$ i = 0;
foreach($ a as $ n =&gt; $ v){
if(strcmp($ n,$ i))return(true) ;
$ i ++;
}
return(false);
}

// cambiar quotes,
y

para devolvercadenasválidasJSON
function qcl2json($ qcl){
return str_replace( ''','\'',str_replace(“
”,'
',str_replace(“”,'',$ qcl)));
}

// devolver变量 en formato json
function ajson($ av,$ level = 0,$ utf8 = false){
if(($ av === null)&amp;&amp;!$ level)return(“null”);
if(!is_array($ av))return(gettype($ av)==“integer”?$ av:'“'。($ utf8?utf8_encode($ av):$ av)。'”');
$ isobj = aputio($ av);
$ i = 0;
if(!$ level)$ e =($ isobj?“{”:“[”); else $ e =“”;
foreach($ av as $ n =&gt; $ v){
if($ i)$ e。=“,”;
if($ isobj)$ e。=( is_numeric($ n)&amp;&amp;!is_string($ n)?$ n:“\”“。​​qcl2json($ utf8?utf8_encode($ n):$ n)。”\“”)。“:”; \ n if(!is_array($ v)){
if(is_bool($ v))$ e。=($ v?“true”:“false”);
if if($ v == NULL)$ e。='“”';
if if(is_int($ v)|| is_double($ v))$ e。= $ v;
else $ e。='“'。qcl2json($ utf8?utf8_encode ($ v):$ v)。''';
} else {
$ e。=(count($ v)
?(aputio($ v)
?“{”。ajson($ v ,$ level + 1)。“}”
:“[”。ajson($ v,$ level + 1)。“]”)
:“{}”);
}
$ i ++; \ n}
if(!$ level)$ e。=($ isobj?“}”:“]”);
return($ e);
}
</ code> </ pre>

如果可以使用UTF-8,请避免使用此功能。</ p>
</ div>

展开原文

原文

json_encode works only with UTF-8 encoded data, so when find a invalid character, it returns NULL for all.

Check your data is encoded in UTF-8.

Also check your file is using UTF-8.

An alternative to json_encode:

// función interna: comprueba si un array es puro o no
// es puro si sus índices son: 0, 1, 2, ..., N
function aputio($a) {
    $i=0;
    foreach ($a as $n=>$v) {
        if (strcmp($n,$i)) return(true);
        $i++;
    }
    return(false);
}

// cambiar quotes, 
 y  para devolver cadenas válidas JSON
function qcl2json($qcl) {
    return str_replace('"','\"',str_replace("
",'
',str_replace("",'',$qcl)));
}

// devolver variable en formato json
function ajson($av,$level=0,$utf8=false) {
    if (($av===null) && !$level) return("null");
    if (!is_array($av)) return (gettype($av)=="integer"?$av:'"'.($utf8?utf8_encode($av):$av).'"');
    $isobj=aputio($av);
    $i=0;
    if (!$level) $e=($isobj?"{":"["); else $e="";
    foreach ($av as $n=>$v) {
        if ($i) $e.=",";
        if ($isobj) $e.=(is_numeric($n) && !is_string($n)?$n:"\"".qcl2json($utf8?utf8_encode($n):$n)."\"").":";
        if (!is_array($v)) {
            if (is_bool($v)) $e.=($v?"true":"false");
            else if ($v==NULL) $e.='""';
            else if (is_int($v)||is_double($v)) $e.=$v;
            else $e.='"'.qcl2json($utf8?utf8_encode($v):$v).'"';
        } else {
            $e.=(count($v)
                ?(aputio($v)
                    ?"{".ajson($v,$level+1)."}"
                    :"[".ajson($v,$level+1)."]")
                :"{}");
        }
        $i++;
    }
    if (!$level) $e.=($isobj?"}":"]");
    return($e);
}

Avoid using this functions if you can use UTF-8.

doujun7161
doujun7161 哇......对我来说,看起来像地狱,| o | o | ,绝对不是新东西。 我保留了以防万一我赶上来。 我解决了问题删除所有以前的回声但回声json_encode,它工作,现在我想发布ARRAYS,这是其他麻烦:)任何建议是欣赏
接近 9 年之前 回复



您的json编码是正确的尝试将此行添加到您的php脚本中,因为IOS可能对响应非常严格。</ p> \ n

将此内容添加到您的php脚本中:</ p>

  header('Content-type:application / json'); 
</ code> </ pre>

除了检查之外,您还匹配参数的情况。 我看到你的PHP脚本发送 id </ code>但看起来你的ios脚本正在寻找 ID </ code> </ p>
</ div>

展开原文

原文

your json encoding is correct try add this line to your php script because IOS may be really strict with the response.

add this to your php script:

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

besides that check you are matching the case of your parameters. I see your php script sends id but looks like your ios script is looking for ID

dongshi4773
dongshi4773 谢谢加布里埃尔,我还没检查过。 你的代码做了什么? 清理其余的回声? 我解决了那部分删除所有回声但json_encode,它工作,现在我想发布ARRAYS,这是其他麻烦:)任何建议是欣赏
接近 9 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐