JSON 解析返回 null 到 iOS(json 字符串看起来正确)

Posted

技术标签:

【中文标题】JSON 解析返回 null 到 iOS(json 字符串看起来正确)【英文标题】:JSON parsing returns null to iOS (json string looks correct) 【发布时间】:2011-08-21 19:14:31 【问题描述】:

我正在尝试获取一个 JSON 到 ios 应用程序,但不断获取 NULL 值..

- (id)initWithDictionary:(NSDictionary *)dictionary 
    self.name      = [dictionary valueForKey:@"name"];
    self.amount    = [NSString stringWithFormat:@"%@", 
                      [dictionary valueForKey:@"amount"]];
    self.goalId    = [dictionary valueForKey:@"id"];
    self.createdAt = [dictionary valueForKey:@"created_at"];
    self.updatedAt = [dictionary valueForKey:@"updated_at"];
    return self;

+ (NSArray *)findAllRemote 
    NSURL *url = [NSURL URLWithString:@"http://localhost:3000/goals.json"];
    NSError *error = nil;
    NSString *jsonString = 
    [NSString stringWithContentsOfURL:url 
                         encoding:NSUTF8StringEncoding 
                            error:&error];

    NSLog(@"my string = %@",  jsonString);

   NSMutableArray *goals = [NSMutableArray array];
   if (jsonString) 
       SBJSON *json = [[SBJSON alloc] init];    
       NSArray *results = [json objectWithString:jsonString error:&error];

       [json release];


       for (NSDictionary *dictionary in results) 
           Goal *goal = [[Goal alloc] initWithDictionary:dictionary];
           [goals addObject:goal];
           [goal release];
        
    
    return goals;    

JSON 字符串看起来正确:

我的字符串 = ["goal":"amount":"100.0","created_at":"2011-08-20T00:55:34Z","id":1,"name":"User" ,"updated_at":"2011-08-20T00:55:34Z","目标":"amount":"200.0","created_at":"2011-08-20T00:56:48Z"," id":2,"name":"User2","updated_at":"2011-08-20T00:56:48Z","goal":"amount":"19999.0","created_at":" 2011-08-20T19:15:10Z","id":3,"name":"这是我的目标","updated_at":"2011-08-20T19:15:10Z","目标" :"amount":"0.0","created_at":"2011-08-20T20:46:44Z","id":4,"name":"goal","updated_at":"2011-08-20T20 :46:44Z"]

我想我错过了一些基本的东西..

更新

这是返回 NULL 的行(来自另一个类):

- (IBAction)refresh 
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
self.goals = [Goal findAllRemote];
[self.tableView reloadData];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;


- (void)viewDidLoad

[super viewDidLoad];

self.title = @"Goals";
self.navigationItem.leftBarButtonItem = self.editButtonItem;

UIBarButtonItem *refreshButton = [[UIBarButtonItem alloc] 
                                      initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
                                  target:self 
                                  action:@selector(refresh)];
self.navigationItem.rightBarButtonItem = refreshButton;
[refreshButton release];

[self refresh];




 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath



static NSString *CellIdentifier = @"GoalCellId";

UITableViewCell *cell = 
[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) 
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1
                                   reuseIdentifier:CellIdentifier] autorelease];


Goal *goal = [goals objectAtIndex:indexPath.row];

cell.textLabel.text = goal.name;
cell.detailTextLabel.text = goal.amount;

return cell;

goal.namegoal.amount 为 Null..

【问题讨论】:

什么被返回为 NULL? 【参考方案1】:

这可能不是您的问题的一部分,但您应该调用[self init](或更重要的是,通过继承调用[super init]):

- (id)initWithDictionary:(NSDictionary *)dictionary 
    if (self = [self init]) 
      self.name      = [dictionary valueForKey:@"name"];
      self.amount    = [NSString stringWithFormat:@"%@", 
                      [dictionary valueForKey:@"amount"]];
      self.goalId    = [dictionary valueForKey:@"id"];
      self.createdAt = [dictionary valueForKey:@"created_at"];
      self.updatedAt = [dictionary valueForKey:@"updated_at"];
    
    return self;

还有:

    for (NSDictionary *dictionary in results) 
       Goal *goal = [[Goal alloc] initWithDictionary:
          [dictionary objectForKey:@"goal"]];
       [goals addObject:goal];
       [goal release];
    

第 3 行中的密钥更改为 [dictionary objectForKey:@"goal"]

JSON 数组包含具有单个 goal 成员的对象,以及您的 initWithDictionary 方法正在寻找的属性。

【讨论】:

这完全有效!非常感谢!!顺便说一句..当我添加 if (self = [self init]) 行时,我收到以下警告:语义问题:使用赋值结果作为不带括号的条件 该警告只是因为编译器确保您在 if 条件中故意进行赋值 (=)(因为您通常需要 ==,用于相等比较)。添加第二组括号(即:((self = [self init])))将抑制警告,因为 = 的这种用法是有意的。

以上是关于JSON 解析返回 null 到 iOS(json 字符串看起来正确)的主要内容,如果未能解决你的问题,请参考以下文章

ios中json解析出现的null问题

json_decode 从 iOS 应用程序返回空值

使用 gson 解析成 POJO 时,Json 总是返回 null

Xcode 解析 JSON 返回 NULL

iOS JSONKit objectWithData 返回 null

ios JSON解析常见错误