如何从此JSON字典中检索数据?

时间:2014-03-20 21:55:00

标签: ios json nsdictionary nsuserdefaults nsjsonserialization

所以我有一个Json字典数据,如下所示

{
merchant =     {
    StoreID = 113;
};
token =     {
    Application = Merchant;
    DatabaseID = 113;
    DeviceToken = 9e7737daf0cb1e0572db47f520797adefd0367f66d5d6056f889732dcdb88772;
    ID = 84;
    LoginToken = "00000000-0000-0000-0000-000000000000";
    OS = iOS;
};
}

之前的数据仅作为"令牌"部分和我将使用以下代码获取数据:

[userdefaults setObject:[json objectForKey:@"LoginToken"] forKey:@"loginToken"];

但是,数据已被修改为两个包装器,我无法获取正确的数据。例如,我如何获得" storeID"来自新数据??

2 个答案:

答案 0 :(得分:3)

您是否已将json-string转换为NSDictionary?

NSString *storeID = [(NSDictionary *)[json objectForKey:@"merchant"] objectForKey:@"StoreID"];

如果不是,您需要先转换它:

NSString *json_string = @"{\"merchant\": {\"StoreID\":\"123\"} }";
NSError *error;
NSDictionary *JSON =
[NSJSONSerialization JSONObjectWithData: [json_string dataUsingEncoding:NSUTF8StringEncoding]
                                options: NSJSONReadingMutableContainers
                                  error: &error];

NSString storeID = JSON[@"merchant"][@"StoreID"];
NSLog(@"storeID: %@", storeID);

// Log output: storeID: 123

答案 1 :(得分:2)

我更喜欢[关键]表示法: NSString *storeID = json[@"merchant"][@"StoreID"];