【问题标题】:JSON Objects between PHP and Objective-CPHP 和 Objective-C 之间的 JSON 对象
【发布时间】:2011-01-29 01:23:46
【问题描述】:

我的 iPhone 应用程序正在从 PHP 网站获取 JSON 对象。

PHP 站点上的对象具有多个整数属性。

从数据库中检索到的属性从数据库返回(它们存储为INT)在 JSON 中如下所示:"seatedplayers":"3"

PHP 代码中修改的属性在 JSON 中如下所示:"currentseat":1

在我的 Obj-c 中,我使用 NSNumberFormatter 来正确格式化它们,如下所示:
[numFormatter numberFromString:[jsonObject objectForKey:@"seatedplayers"]];(jsonObject 是 NSDictionary

该代码在值周围有引号的属性上运行良好,但在其他属性上却不行。如果我在我的 Objective-C 代码中添加 stringValue 它适用于不带引号的属性,但不适用于带引号的属性。

现在,我最大的问题是,这个应用程序需要与我不会亲自编写的站点进行通信,那么我可以在 Objective-C 中编写什么代码来处理这两个实例?

编辑
这就是我获得 NSDictionary jsonObject 的方式。

- (NSDictionary *) getJSONObjectFromWebAddress:(NSString *) address {
// Prepare the URL Request
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:address]];

// Perform the request, expecting JSON back
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

NSError *error;
SBJsonParser *parser = [[SBJsonParser new] autorelease];
NSDictionary *jsonObject = [parser objectWithString:responseString error:&error];
if (!jsonObject) {
    NSLog(@"%@", error);
}

[responseString release];
return jsonObject;
}

【问题讨论】:

  • stringValue 是什么?你是如何获得带有 json 值的 NSDictionary 的?我个人会使用 NSScanner,或者用纯 C 写一些东西。
  • 在问题中添加了我如何将其作为 NSDictionary 获得的答案。我会查找 NSScanner,因为我不知道它是什么。
  • 嗯,这很奇怪,帮助我解决问题的答案被删除了,我不记得作者是谁了。

标签: php objective-c json


【解决方案1】:

我遇到了同样的问题。幸运的是,NSString 和 NSNumber 都响应 intValue,所以你可以放心地使用它。


//NSDictionary* myJsonParsed;
[NSString stringWithFormat:@"%d", [[myJsonParsed valueForKey:@"stringOrInt"] intValue]];

【讨论】:

  • intValue 是否返回 NSNumber?这就是我在 Objective-C 中的类型(它们是 CoreData 对象)。
  • intValue 返回一个 C int。您可以通过调用[NSNumber numberWithInt:[[myJsonParsed valueForKey:@"stringOrInt"] intValue]]; 创建一个 NSNumber
猜你喜欢
  • 1970-01-01
  • 2012-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-25
  • 1970-01-01
  • 2011-06-25
  • 2017-10-25
相关资源
最近更新 更多