如何在ARRAY / String中存储JSON的值

时间:2011-05-18 12:09:58

标签: iphone objective-c ios4 iphone-sdk-3.0

我有以下JSON值:

-(
            { Key   = IsEmail;
              Value = 1;     },

            { Key   = TrackingInterval;
              Value = 20;    },

            { Key   = IsBackup;
              Value = 1;     },

            { Key   = WipeOnRestore;
              Value = 1;     }
)

我如何将此对象解析为数组或字符串? - 即要存储在数组中的eack 值,并将每个存储在另一个数组中。

请帮我解决这个问题。

谢谢:)

4 个答案:

答案 0 :(得分:4)

此方法使用json-framework

我缩短了你的例子:

NSString *jsonString = @"[{\"Key\":\"IsEmail\",\"Value\":\"1\"},{\"Key\":\"TrackingInterval\",\"Value\":\"20\"},{\"Key\":\"IsBackup\",\"Value\":\"1\"}]";

NSMutableArray *keys = [NSMutableArray array];
NSMutableArray *values = [NSMutableArray array];    

NSArray *json = [jsonString JSONValue];

for (NSDictionary *pair in json) {
    [keys addObject:[pair objectForKey:@"Key"]];
    [values addObject:[pair objectForKey:@"Value"]];        
}

NSLog(@"%@", keys); 
NSLog(@"%@", values);

输出:

2011-05-18 14:23:55.698 [36736:207] (
    IsEmail,
    TrackingInterval,
    IsBackup
)
2011-05-18 14:23:55.700 [36736:207] (
    1,
    20,
    1
)

答案 1 :(得分:1)

答案 2 :(得分:0)

您的数据无效json,您可能希望将其构造得更像这样:

var theObj = { IsEmail: 1, TrackingInterval: 20, IsBackup: 1, WipeOnRestore: 1 };

然后你可以填充像这样的键和值数组:

var keys = new Array();
var values = new Array();

for (prop in theObj) {
    keys.push(prop);
    values.push(theObj[prop]);
}

答案 3 :(得分:0)

如果JSON采用以下格式,

responseString=[ {
        Key = IsEmail;
        Value = 1;
    },
            {
        Key = TrackingInterval;
        Value = 20;
    },
            {
        Key = IsBackup;
        Value = 1;
    },
            {
        Key = WipeOnRestore;
        Value = 1;
    }] 

 then,

NSArray *resultArray=[responseSrting JSONValue];

NSMuatbleArray *keyArray=[[NSMutableArray alloc] init];

NSMutableArray *valueArray=[[NSMutableArray alloc] init];

for(NSDictionary *dict in resultsArray){

[keyArray addObject:[dict objectForKey:@"Key"]];

[valueArray addObject:[dict objectForKey:@"Value"]];

}

然后,所有密钥都存储在keyArray中,所有值都存储在valueArray中