【问题标题】:very basic JSON to tableView (iOS)非常基本的 JSON 到 tableView (iOS)
【发布时间】:2012-07-31 02:18:16
【问题描述】:

好吧,我决定是时候学习一项新技能了,那就是 Objective-c 编程。我的编程知识非常少,它由 PHP、一点点 HTML 和一点点 MySQL 组成。我想要做的是获取一些用 php 制作的 JSON 并填充 iOS 表格视图。

这是我的 json.php:

<?php
$array = array(1,2,3,4,5,6,7,8,9,10);
$json = json_encode($array);
echo $json;
?>

我唯一的问题是,我不知道如何开始使用 JSONKit 框架。 https://github.com/johnezang/JSONKit/ 我更喜欢使用 JSONKit 而不是其他替代品,因为它似乎有更多的支持。

NSString *strURL = [NSString stringWithFormat:@"http://api.tekop.net/json.php"];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSLog(@"%@", strResult);

我能够在调试控制台中打印 JSON 页面的结果。现在我唯一的问题是下一步是什么?我试图在网上寻找一些教程,但我能找到的只是更高级的 Jason 短语。为了满足我的基本需求。我知道我的问题非常模糊,并且对很多不同的答案持开放态度,但我认为这是提出这类问题的地方。

【问题讨论】:

    标签: php objective-c json uitableview jsonkit


    【解决方案1】:

    iOS 有自己的 JSON 解析,现在称为 NSJSONSerialization。

    http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html

    你可以看看。我一直都是这样用的。

    [NSJSONSerialization JSONObjectWithData:tmpData
                                           options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments 
                                             error:nil]
    

    通过修改您的代码进行示例:

    NSString *strURL = [NSString stringWithFormat:@"http://api.tekop.net/json.php"];
    NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
    NSArray *arrayResult = [NSJSONSerialization JSONObjectWithData:dataURL
                                           options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments 
                                             error:nil];
    
    NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
    

    需要注意的是,如果您的 json 是基于数组的,请使用 NSArray 来存储结果。如果您的 json 是基于哈希的,请使用 NSDictionary。 (希望我说清楚,我不知道描述的相关术语)

    【讨论】:

      【解决方案2】:

      你试过什么?

      NSArray *array = [dataURL objectFromJSONData];
      NSAssert([array isKindOfClass:[NSArray class]], @"This should be an array.");
      
      for (NSNumber *value in array) {
          NSAssert([value isKindOfClass:[NSNumber class]], @"This should be a number.");
      
          NSLog(@"%@", value);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多