包含NSString数组的JSON

时间:2014-07-19 23:04:41

标签: 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
            );
        }
    );
}

1 个答案:

答案 0 :(得分:1)

只需遵循结构。

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
}