简体   繁体   English

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

[英]How can I retrieve the data from this JSON dictionary?

So I have a Json dictionary data coming in like below 所以我有一个Json字典数据如下

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

The data came in before as just the "token" part and I would get the data by using the following code: 数据只是作为“令牌”部分输入的,我将使用以下代码获取数据:

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

However, the data has been modified into two wrappers and I can't grab the correct data. 但是,数据已被修改为两个包装,我无法获取正确的数据。 How can I, for example, get the "storeID" from the new data?? 例如,如何从新数据中获取“ storeID”?

Did you already convert your json-string to a NSDictionary? 您是否已经将json-string转换为NSDictionary?

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

If not you need to convert it first: 如果不是,则需要先将其转换:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM