NSArray/NSDictionary 对象与 json 字符串的相互转换

Objective C 2020-04-06 阅读 577 评论 0

iOS中,使用 Objective C 的 NSJSONSerialization 类,实现 JSON 字符串与对象(如字典、数组等)的相互转换。

将对象转化为字符串

使用 dataWithJSONObject:options:error: 方法。options 为 NSJSONWritingOptions,包括4个枚举。

  1. NSJSONWritingPrettyPrinted。使用空格和缩进的写入选项使输出更具可读性。
  2. NSJSONWritingSortedKeys。按字典顺序对键进行排序的写入选项。
  3. NSJSONWritingFragmentsAllowed。
  4. NSJSONWritingWithoutEscapingSlashes。
// 字典
NSDictionary *dictionaryOrArray = @{@"value": @"blue", @"key": @"color"};
// 数组
// NSArray *dictionaryOrArray = @[@"color", @"blue"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryOrArray
                                                   options:NSJSONWritingPrettyPrinted
                                                     error:&error];

if (error) {
    NSLog(@"Got an error: %@", error);
} else {
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"%@", jsonString);
}

将字符串转换为对象

使用 JSONObjectWithData:options:error: 方法。

options 为NSJSONReadingOptions,包括4个枚举

  1. NSJSONReadingMutableContainers。返回可变容器,NSMutableDictionary或NSMutableArray。
  2. NSJSONReadingMutableLeaves。JSON对象中的被创建的字符串是NSMutableString类型。
  3. NSJSONReadingAllowFragments。允许JSON字符串最外层既不是NSArray也不是NSDictionary,但必须是有效的JSON Fragment。
  4. NSJSONReadingFragmentsAllowed。

NSJSONReadingAllowFragments 与 NSJSONReadingFragmentsAllowed 的使用举例,例如可以将 @"32" 解析为 32(NSNumber 类型),@"\"32\"" 解析为 @"32"NSString 类型)。

NSString *jsonString = @"{ \"colors\": [ \"red\", \"green\" ] }";
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSMutableDictionary *data = [NSJSONSerialization JSONObjectWithData:jsonData
                                                   options:NSJSONReadingAllowFragments
                                                     error:&error];

if (error) {
    NSLog(@"Got an error: %@", error);
} else {
    NSLog(@"%@", data);
}
最后更新 2020-04-06
MIP.watch('startSearch', function (newVal, oldVal) { if(newVal) { var keyword = MIP.getData('keyword'); console.log(keyword); // 替换当前历史记录,新增 MIP.viewer.open('/s/' + keyword, {replace: true}); setTimeout(function () { MIP.setData({startSearch: false}) }, 1000); } }); MIP.watch('goHome', function (newVal, oldVal) { MIP.viewer.open('/', {replace: false}); });