我可以最小化此 SBjson 代码中使用的对象数量吗?

发布于 2024-12-09 02:02:51 字数 550 浏览 1 评论 0原文

我从服务器收到的响应的格式如下:

{
    "Data":{
        "Key": "Value"
        ...
    },
    "Key": "Value"
    ...
}

但是,我只对“数据”下的元素感兴趣。 这是我当前使用的代码:

SBJsonParser *parser = [SBJsonParser new]; 
NSString *responseString = [request responseString];
NSDictionary *responseData = [parser objectWithString:responseString];
NSString *infoString = [responseData objectForKey:@"Data"];
NSDictionary *infoData = [parser objectWithString:infoString];

有没有一种方法可以在不显式声明 5 个对象的情况下执行相同的操作?只是寻找一些我应该使用的速记方式。

The response I receive from the server is formatted as such:

{
    "Data":{
        "Key": "Value"
        ...
    },
    "Key": "Value"
    ...
}

However, I am only interested in the elements under "Data".
Here is the code I'm currently using:

SBJsonParser *parser = [SBJsonParser new]; 
NSString *responseString = [request responseString];
NSDictionary *responseData = [parser objectWithString:responseString];
NSString *infoString = [responseData objectForKey:@"Data"];
NSDictionary *infoData = [parser objectWithString:infoString];

Is there a way to perform the same thing without explicitly declaring 5 objects? Just looking for some sense of short-hand that I should be using.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

感性 2024-12-16 02:02:51

你的最后两行是错误的 - "Data" 实际上是一个 NSDictionary,所以你不需要双重解析它。

此外,大多数 Objective-C 程序员都会在他们知道返回是安全的地方嵌套调用 - 我的意思是不需要额外的检查。例如,这对我来说是一个更自然的实现:

NSDictionary *responseDictionary = [[request responseString] JSONValue];
NSDictionary *infoData = [responseDictionary objectForKey:@"Data"];

请注意,我正在使用 SBJSON 附带的 NSObject 类别中的便捷方法 JSONValue

Your last two lines are wrong - "Data" is actually an NSDictionary, so you don't need to double parse it.

Also, most objective-C programmers would nest calls where they know that the returns are safe - by which I mean don't need additional checking. For instance, this would see a more natural implementation to me:

NSDictionary *responseDictionary = [[request responseString] JSONValue];
NSDictionary *infoData = [responseDictionary objectForKey:@"Data"];

Note that I am using the convenience method JSONValue from the category on NSObject that comes with SBJSON.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文