SHValue
处理 Objective-C 中 JSON 数据的安全方式
为什么在 Objective-C 中处理 JSON 的典型方法有必要?
代码看起来像这样
NSDictionary *jsonDict = @{@"data": @[@{}, @{}, @{@"name": @"A"}]};
if ([jsonDict isKindOfClass:[NSDictionary class]]) {
if ([jsonDict[@"data"] isKindOfClass:[NSArray class]]) {
NSArray *array = jsonDict[@"data"];
if (array.count > 2) {
NSString *name = array[2];
// Finally we got the name
}
}
}
这不好。
使用 SHValue,您只需这样做
NSDictionary *jsonDict = @{@"data": @[@{}, @{}, @{@"name": @"A"}]};
NSString *name = [SHValue value:jsonDict][@"data"][2].string;
// There's our name
NSString *str = [SHValue value:jsonDict][@"a"][@"b"][@"c"][100].string;
// str is nil, but it won't crash.
不用担心越界访问问题。这是自动且安全完成的。
字符串属性是可空的(Optional),stringValue 是非可选字符串。即使没有值,stringValue 也会返回 ""。它还支持数组、字典和数字,包括可选和非可选的。
要求
- iOS 8.0+ | macOS 10.10+ | tvOS 9.0+ | watchOS 2.0+
- Xcode 8
集成
CocoaPods (iOS 8+, OS X 10.9+)
您可以使用 CocoaPods 将 SHValue
添加到您的 Podfile
中以安装它。
platform :ios, '8.0'
use_frameworks!
target 'MyApp' do
pod 'SHValue'
end
请注意,这需要 CocoaPods 版本 36,并且您的 iOS 布署目标至少为 8.0。