以下是我的数据示例:
[
{
code: "DRK",
exchange: "BTC",
last_price: "0.01790000",
yesterday_price: "0.01625007",
top_bid: "0.01790000",
top_ask: "0.01833999"
}
]
我正在尝试通过将我的NSDictionary的内容加载到Array中来检索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没有root元素,所以我该怎么办?
此外,使用建议的答案时,输出为(“...
- (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];
}
答案 0 :(得分:1)
使用NSArray
将JSON转换为NSJSONSerialization
。然后访问值:
NSData *darkData = [@"[{\"code\":\"DRK\",\"exchange\": \"BTC\",\"last_price\": \"0.01790000\",\"yesterday_price\": \"0.01625007\",\"top_bid\": \"0.01790000\"}, {\"top_ask\": \"0.01833999\"}]" dataUsingEncoding:NSUTF8StringEncoding];
NSArray *array = [NSJSONSerialization JSONObjectWithData:darkData
options:0
error:&error];
NSString *value = array[0][@"last_price"];
NSLog(@"value: %@", value);
NSLog输出:
值:0.01790000
如果您在发布已编写的代码时遇到问题需要帮助。
- 针对新的OP代码进行了更新:
Web服务返回JSON 数组或词典而不是JSON 词典。首先,您必须索引数组,然后索引到字典中。
NSURL *darkURL = [NSURL URLWithString:@"https://api.mintpal.com/v1/market/stats/DRK/BTC"];
NSData *darkData = [NSData dataWithContentsOfURL:darkURL];
NSError *error = nil;
NSArray *darkArray = [NSJSONSerialization JSONObjectWithData:darkData options:0 error:&error];
NSDictionary *darkDict = darkArray[0];
NSString *lastP = [darkDict valueForKey:@"last_price"];
NSLog(@"lastP: %@", lastP);
NSLog输出:
lastP:0.01970000
请注意两行:
NSDictionary *darkDict = darkArray[0];
NSString *lastP = [darkDict valueForKey:@"last_price"];
可以使用数组索引替换为单行:
NSString *lastP = darkArray[0][@"last_price"];
" [0]"获取第一个数组元素NSDictionary
和" [@" last_price"]"从字典中获取名称项。
答案 1 :(得分:1)
看起来你想要迭代你的结果。根元素是一个数组而不是字典,所以你可以开始迭代
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"];