ios - 包含 NSString 数组的 JSON

标签 ios objective-c json ios7

如何从我实例化的 NSDictionary 中提取每个地址(如下),以便我可以分配给各种 NSString 对象?

我有以下 JSON:

{
   "Address":[
      {
         "$":{
            "ID":"0"
         },
         "Address2":[
            "10 Smith RD"
         ],
         "City":[
            "Mapleville"
         ],
         "State":[
            "NJ"
         ],
         "Zip5":[
            "90210"
         ],
         "Zip4":[
            "764"
         ]
      },
      {
         "$":{
            "ID":"1"
         },
         "Address2":[
            "32 Hog CT"
         ],
         "City":[
            "New York City"
         ],
         "State":[
            "NY"
         ],
         "Zip5":[
            "90210"
         ],
         "Zip4":[
            "1390"
         ]
      }
   ]
}

cData(如下)来自上面的 JSON。 我执行了以下操作来转换为 NSDictionary:

NSDictionary* dictionary2 = [NSJSONSerialization JSONObjectWithData:cData options:NSJSONReadingAllowFragments error:nil];

一旦我做了:

NSLog(@"%@", dictionary2);

NSLog 的输出:

{
    Address =     (
                {
            "$" =             {
                ID = 0;
            };
            Address2 =             (
                "10 Smith RD"
            );
            City =             (
                "Mapleville"
            );
            State =             (
                NJ
            );
            Zip4 =             (
                7642
            );
            Zip5 =             (
                90210
            );
        },
                {
            "$" =             {
                ID = 1;
            };
            Address2 =             (
                "32 Hog CT"
            );
            City =             (
                "New York City"
            );
            State =             (
                NY
            );
            Zip4 =             (
                1390
            );
            Zip5 =             (
                90210
            );
        }
    );
}

最佳答案

只要遵循结构即可。

NSDictionary* dictionary2 = [NSJSONSerialization ...
NSArray *addresses = dictionary2[@"Address"];
for (NSDictionary *addressData in addresses) {
    NSString *address2 = addressData[@"Address2"];
    NSString *city = addressData[@"City"];
    // and the rest as needed
}

关于ios - 包含 NSString 数组的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24845777/

相关文章:

objective-c - 从 URL 打开 iOS 应用程序并传递参数

javascript - 在 accounting.js 中使用 money.js 的问题

java - jackson 反序列化带有额外字段的 map

ios - 如何将多个地名转换成坐标?

ios - Google Maps SDK Logo 选项

objective-c - Objective-C 中的 Try-Catch 等价物

javascript - 为什么 JSON.stringify 为似乎具有属性的对象返回空对象符号 "{}"?

objective-c - 带有 SBJSON 的 NSData 或 NSAttributedString

ios - 如何使用 Storyboard将两个不同的选项卡栏图标连接到同一个 View Controller ?

objective-c - NSMutableArray 空数组错误