0

基本的に、WebページにJSON配列があり、配列はWebページで正常に機能し、それを文字列としてobjective-cにプルできますが、配列としてobjective-cにプルする必要があります。これを行う最も基本的な方法を誰か教えてもらえますか? これを行うチュートリアルをいくつか見たことがありますが、それらのほとんどは JSON のオブジェクトの配列です。

文字列として情報を取得するための私の客観的な c コードは次のとおりです。

//create string to contain URL address for PHP file, the file name is index.php and the parameter: name is passed to the file
NSString *strURL = [NSString stringWithFormat:@"http://localhost:8888/page4.php?name=%@", _txtName.text];

//to execute PHP code
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString: strURL]];

//to recieve the returned value
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];


NSLog(@"%@", strResult);

これが私のウェブページの PHP/JSON コードです。

<?php

if (isset ($_GET["name"]))
        $name = $_GET["name"];
    else
        $name = "NULL";

// Make a MySQL Connection
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
// Retrieve all the data from the "example" table
$result = mysql_query("SELECT * FROM user WHERE name = '$name'")
or die(mysql_error());  
// store the record of the "example" table into $row
$row = mysql_fetch_array( $result );

$array = array(
"0" => $row['id'],
"1" => $row['name'],
);


$json_array = json_encode($array);
echo $json_array;

?>
4

2 に答える 2

2

次のコードを使用して、json 応答を配列に変換できます

    NSError* error = nil;
    NSArray *jsonArray = [NSJSONSerialization
                          JSONObjectWithData:responseData
                          options:kNilOptions 
                          error:&error];
于 2013-03-29T15:17:21.790 に答える
2

iOS 5 以降、Apple はこれを行う組み込みクラスを提供しています。オプションを設定して、返されたオブジェクトNSArrayNSDictionaryコンテナーを変更可能にするか、または返されたリーフ オブジェクトを変更可能にすることができます。NSDataではなく で動作しNSStringます。使い方は簡単です:

NSError *error = nil;
NSArray *parsedArray = [NSJSONSerialization JSONObjectWithData:dataUrl
                                                       options:kNilOptions
                                                         error:&error];
于 2013-03-29T15:17:29.247 に答える