iOS 正在创建一个没有 {} 的 JSON 字符串——只有 [ ]?

标签 ios json

为什么赋值给 jsonString 不包括大括号{}?

这是我得到的:

["anemail@chdr.com"]

代码

if (_allEmails)
        {
            NSError *error = nil;
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:_allEmails options:0 error:&error];
            if (!error)
            {

                NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

                [dictionary setObject:jsonString forKey:@"AllEmails"];
            }
        }

最佳答案

_allEmails 变量必须是一个数组(你告诉我),对于大括号,你需要将数据存储在字典中。

也许您正在寻找的是:

if ([_allEmails count] > 0)
{
    NSError *error = nil;
    NSDictionary *dict = @{ @"AllEmails" : _allEmails };
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
                                                       options:0
                                                         error:&error];
    // Note: Check returned object and not NSError object
    if (jsonData) {
        NSString *jsonString = [[NSString alloc] initWithData:jsonData
                                                     encoding:NSUTF8StringEncoding];
        // Do thing with string
    } else {
        NSLog(@"Failed to serialize JSON: %@", [error localizedDescription]);
    }
}

关于iOS 正在创建一个没有 {} 的 JSON 字符串——只有 [ ]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25209199/

相关文章:

python - 如何从 selenium python 中获取 JSON

javascript - JSON - 对象中的数组中的对象 - 如何使用 JS 解析循环?

json - 将扩展属性序列化为 JSON

javascript - 如何在 Controller 中格式化 JSON 数据

ios - 来自 XIB : contentView width is always the same 的自定义 UITableViewCell

iphone - UIPageControl 子类重写

ios - 多个 Controller 的快速通知

ios - ios中每个触摸点有一个指针吗

ios - 动画阵列不动画 Sprite

ruby-on-rails - 新的 Rails 3,带有 json 响应的 ajax 请求