【问题标题】:The most basic way to retrieve a JSON array in objective-c? [duplicate]在objective-c中检索JSON数组的最基本方法是什么? [复制]
【发布时间】:2013-03-29 15:12:55
【问题描述】:

基本上我在网页上有一个 JSON 数组,该数组在网页上工作正常,我可以将它作为字符串拉入 Objective-c,但我需要将它作为数组拉入 Objective-c。谁能告诉我最基本的方法吗?我看过一些这样做的教程,但其中大多数是 JSON 中的对象数组。

这是我将信息作为字符串提取的 Objective-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;

?>

【问题讨论】:

  • 基本是低技术的意思?把它写在一张纸上,然后用小瓶蜗牛邮件发送……

标签: objective-c arrays json parsing


【解决方案1】:

从 iOS 5 开始,Apple 提供了一个内置类来为您执行此操作。您可以设置选项以使返回的NSArrayNSDictionary 容器可变,或返回的叶对象可变。它在NSData 上运行,而不是NSString。使用简单:

NSError *error = nil;
NSArray *parsedArray = [NSJSONSerialization JSONObjectWithData:dataUrl
                                                       options:kNilOptions
                                                         error:&error];

【讨论】:

    【解决方案2】:

    您可以使用以下代码将您的 json 响应转换为数组

        NSError* error = nil;
        NSArray *jsonArray = [NSJSONSerialization
                              JSONObjectWithData:responseData
                              options:kNilOptions 
                              error:&error];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-22
      • 1970-01-01
      • 2011-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多