【问题标题】:Accessing json structure to capture data in iOS.访问 json 结构以在 iOS 中捕获数据。
【发布时间】:2014-04-04 09:06:27
【问题描述】:

我有以下代码,它在一定程度上可以工作:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    NSString *strURL = [NSString stringWithFormat:@"http://localhost:8888/service.php"];
    NSURL *url = [NSURL URLWithString:strURL];

    NSData * data = [NSData dataWithContentsOfURL:url];
    NSError * error;
    NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

    AdObject *someAdObject = [[AdObject alloc] init];



    //NSLog(@"%@", json);
    self.detailLabel.text = self.tempString;

}

现在,当注释掉的 NSLog 实际打印 JSON 字典时,我得到:

        {
        brand = "";
        category = Games;
        country = "Japan";
        "discount_rate" = 50;
        duration = 5;
        id = 1;
        "issue_date" = "2014-04-07";
        location = "Heishi Mall";
        title = "Gamestory videogames sales!";
        user = "";
    }
)

我创建了一个 Ad 对象,它具有标题、位置、国家等属性(如上所示)。我想访问上面的JSON 并将值存储在对象变量中。

【问题讨论】:

    标签: ios iphone objective-c json viewdidload


    【解决方案1】:

    您可以访问该值:-

     for(NSDictionary *item in json) {                  
        NSLog(@"%@",[item valueForKey:@"key"]);
       someAdObject.key  = [item valueForKey:@"key"];                 
     }
    

    【讨论】:

    • @spacemonkey 有用吗?
    • 是的,不可能一直是我的朋友。感谢昨天和今天的支持
    【解决方案2】:

    试试这个并检查你的json

    AdObject *someAdObject = nil;
    for(NSDictionary *item in json) {
        someAdObject = [[AdObject alloc] init];
        someAdObject.category = [item valueForKey@"category"]; 
        someAdObject.country = [item valueForKey@"country"]; 
        someAdObject.discount_rate = [item valueForKey@"discount_rate"]; 
        someAdObject.duration = [item valueForKey@"duration"]; 
        //and same all of your required object properties
    }
    

    【讨论】:

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