这是我的数据的示例:
[
{
code: "DRK",
exchange: "BTC",
last_price: "0.01790000",
yesterday_price: "0.01625007",
top_bid: "0.01790000",
top_ask: "0.01833999"
}
]
我试图通过将NSDictionary的内容加载到数组中来检索last_price的值。
NSURL *darkURL = [NSURL URLWithString:@"https://api.mintpal.com/v1/market/stats/DRK/BTC"];
NSData *darkData = [NSData dataWithContentsOfURL:darkURL];
NSError *error = nil;
NSDictionary *darkDict = [NSJSONSerialization JSONObjectWithData:darkData options:0 error:&error];
self.darkPosts = [NSMutableArray array];
NSArray *darkPostArray = [darkDict objectForKey:@""];
for (NSDictionary *darkDict in darkPostArray) {...
但是我的json没有根元素,该怎么办?
此外,使用建议的答案时,输出为(“ ...
- (void)viewDidLoad{
[super viewDidLoad];
NSURL *darkURL = [NSURL URLWithString:@"https://api.mintpal.com/v1/market/stats/DRK/BTC"];
NSData *darkData = [NSData dataWithContentsOfURL:darkURL];
NSError *error = nil;
NSDictionary *darkDict = [NSJSONSerialization JSONObjectWithData:darkData options:0 error:&error];
NSString *lastP = [darkDict valueForKey:@"last_price"];
self.dark_label.text = [NSString stringWithFormat: @"%@", lastP];
}
最佳答案
看来您想遍历结果。根元素是一个数组,而不是字典,因此您可以开始迭代
NSError *error = nil;
NSArray *items = [NSJSONSerialization JSONObjectWithData:darkData
options:kNilOptions
error:&error];
if (!items) {
NSLog(@"JSONSerialization error %@", error.localizedDescription);
}
for (NSDictionary *item in items) {
NSLog(@"last_price => %@", item[@"last_price"]);
}
如果您只是想收集last_price的数组,则可以这样做
NSArray *lastPrices = [items valueForKey:@"last_price"];
关于ios - 使用NSArray和NSDictionary访问没有根元素的JSON对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23962808/