如何返回多个JSON结果

时间:2014-02-28 20:09:06

标签: ios objective-c json

我已经构建了一个连接到我的Sql DB的Web服务,并通过JSON返回所请求的数据量。

如果它返回一个记录,一切都很好,但是如果它返回多个,那么整个东西就会在for循环中死掉。任何人都可以指出我正确的方向,找出它为什么这样做。

NSString *urlString;
urlString = @"http://url.php";

NSData *jsonSource = [NSData dataWithContentsOfURL:
                      [NSURL URLWithString:urlString]];

id jsonObjects = [NSJSONSerialization JSONObjectWithData:
                  jsonSource options:NSJSONReadingMutableContainers error:nil];
for (NSDictionary *dataDict in jsonObjects) {
    NSString *idData = [dataDict objectForKey:@"ID"];
 dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                  idData, @"ID",
 Nil];
 [myObject addObject:dictionary];

我正在尝试将这些数据放入表视图中。

JSON是:

[
    {
        "ID": "8",
        "APP_ID": "xx",
        "NAME": "xxx",
        "PRICING": "paid",
        "PRODUCT_ID": "xxx",
        "TITLE‌​": "xxx",
        "INFO": "xxx",
        "DATE": "2014-01-01 00:00:00",
        "AVAILABILITY": "published",
        "COVER": "xxxx",
        "URL": "xxxx",
        "ITUNES_SUMMARY‌​": "In this issue we interview Steve Jobs on all things Apple.",
        "ITUNES_COVERART_URL": "xxx",
        "ITUNES_PUBLISHED": "2012-11-01T00:00:00-07:0‌​0",
        "ITUNES_UPDATED": "2012-11-01T00:00:00-07:00"
    }
]

以下是生成JSON输出的PHP:

if($result = $con->query("SELECT * FROM ISSUES WHERE PRICING = 'free'")) { 
    $tempArray = array(); 
    while($row = $result->fetch_object()) { 
        $tempArray = $row; 
        array_push($json, $tempArray); 
        echo json_encode($json);
    }
 }

2 个答案:

答案 0 :(得分:2)

您确定响应是有效的JSON吗?将JSON数据转换为字符串并将其打印到控制台...

NSLog(@"%@", [[NSString alloc] initWithData:jsonSource encoding:NSUTF8StringEncoding]);

...然后在JSONLintJSON Editor Online等JSON验证程序中进行检查。

您还可以在NSError方法中将指针传递给NSJSONSerialization对象。也可以将其记录到控制台。

NSError *error;
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonSource
                                                 options:NSJSONReadingMutableContainers
                                                   error:&error];
NSLog(@"error %@", error);

如果没有任何错误消息,那么您应该检查的最后一件事是生成的jsonObjects变量是您期望的类型(我假设您期望NSArray)。


看到PHP代码后,这应该可以解决问题:

if($result = $con->query("SELECT * FROM ISSUES WHERE PRICING = 'free'")) { 
    $tempArray = array(); 
    while($row = $result->fetch_object()) {
        array_push($row, $tempArray); 
    }
    echo json_encode($tempArray);
}

答案 1 :(得分:2)

您的服务器似乎只是连接JSON数组

[ { "ID":"1", ... } ] [ { "ID":"2", ... } ] ...

这是无效的JSON,NSJSONSerialization将在阅读第一个后停止 JSON块,将其余部分视为垃圾。

服务器必须返回一个包含多个词典的数组:

[ { "ID":"1", ... }, { "ID":"2", ... }, ... ]
相关问题