【发布时间】:2015-09-22 22:21:56
【问题描述】:
我正在尝试创建一个 Web 服务,通过 php 从 mysql 数据库提供 json 以在 iPhone 应用程序中显示。
我有一个标准的 mysql/php 设置。
数据位于包含字段和记录的表中。用sql查询创建记录集。记录集中的每条记录都是一行。
php
$sql = "SELECT userid,task,longtask FROM tasks WHERE userid = 1 LIMIT 1";
$res = mysql_query($sql) or die(mysql_error());
$tasks = array();
while($row = mysql_fetch_assoc($res)) {
$tasks[] = array('row'=>$row);
}
echo json_encode(array('tasks'=>$tasks));
//
Web 服务产生以下输出:
{"tasks":[{"row":{"userid":"1","task":"send email to Bob","longtask":"include attached memo"}}]}
但是,我在将其读入 IOS 时遇到了很多麻烦,这表明 Web 服务可能有更好的格式。
结构不同于我在教程和其他资源中找到的用于将 json 读入 IOS(均不使用 php/mysql)的结构。
谁能告诉我一个更好的方式来构造 json 或者代码来在 iOS 中读取这个 json 来获取用户 ID、任务和其他变量。
当我尝试这个时,我得到一个错误,它不能在 index:0 处显示行
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSLog(@"about to print json: %@",json);
NSMutableArray *getElement = [json objectForKey:@"tasks"];
for (NSDictionary *dict in getElement) {
NSArray *array = [dict objectForKey:@"row"];
NSString *str = [array objectAtIndex:0];
}
提前感谢您的任何建议。
【问题讨论】:
-
你试过laravel.com框架吗?
-
在我真正理解发生了什么之前尽量避免使用框架。我正在寻找 json 格式,即什么是字典,什么是数组,以及您是否可以在服务器输出中控制这一点令人困惑。