【发布时间】:2014-08-13 09:58:02
【问题描述】:
说你这样做,
NSString *teste = yourData[@"title"];
如果 "title" 在 json 中完全丢失,没问题:你只需得到 null。如果你这样做:
NSString *teste = yourData[@"location"][@"city"];
如果 json 嵌套中缺少 "city",没问题。如果整个"location" 部分不存在,同样没问题
但是!你会经常看到这样的json," largeImage = "<null>"; "
在这种情况下,如果您使用上面的代码,应用程序将会崩溃。
实际上你必须这样做:
NSString *imageUrl = nil;
if ([yourResults[thisRow][@"largeImage"] isKindOfClass:[NSDictionary class]])
imageUrl = yourResults[thisRow][@"largeImage"][@"URL"];
我的问题是:
是否有一些非常聪明的方法可以覆盖文字语法(即,覆盖底层消息,也许??)来解决这个问题?
所以本质上,使这个概念[@"blah"] 基本上首先检查它确实是一本字典,然后再尝试操作。
很遗憾,因为实际上你永远无法使用这种美妙的语法
yourData[@"location"][@"city"]
实际上,由于我概述的问题。
PS 很抱歉之前对这个问题的困惑,由 Paramag 修复。下面 - 好一个 Paramag。
【问题讨论】:
-
But if the whole "location" section does not exist, then ... your iPhone crashes.- 什么?不。然后你向nil发送一条消息,这是一个安全的无操作。
标签: ios json objective-c-literals