簡體   English   中英

目標C訪問元​​素

[英]Objective C Accessing Elements

我正在嘗試獲取從字典中提取的元素並將其轉換為雙精度。 數據是從JSON中提取的,似乎已提取到一種數組類型(不確定哪種類型)中。 有沒有辦法從數組中單獨獲取下面列出的數字? 如果您需要更多信息,請告訴我。

NSDictionary *parameters = @{@"username":savedUser,@"password":savedPass};

        NSURL *URL = [NSURL URLWithString:@"testwebsite"];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [manager GET:URL.absoluteString parameters:parameters progress:nil success:^(NSURLSessionTask *task, id responseObject)
         {

             NSError *error = nil;
             JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
             if (error) {
                 NSLog(@"Error serializing %@", error);
             }
             NSLog(@"%@",JSON);
             NSString *price = [NSString stringWithFormat:@"%@",[JSON valueForKey:@"UnitPrice"]];
             price= [price stringByReplacingOccurrencesOfString:@"\"" withString:@""];

             NSLog(@"Price: %@",price);

             [transactionTotals addObject:price];

             [self createGraph:100];

         }
             failure:^(NSURLSessionTask *operation, NSError *error)
         {

             NSLog(@"Error1: %@", [error debugDescription]);
             NSLog(@"Error2: %@", [error localizedDescription]);

         }];
    }
    @catch (NSException *exception)
    {
        NSLog(@"%@",exception);
    }

日志(我需要單獨提取的單價值):

字典輸出:

2016-07-03 22:52:21.330 T2PApp[2272:658440] (
        {
        OrderDetailID = 3;
        ProductName = Oranges;
        UnitPrice = "399.99";
        date = "2016-06-09T21:45:06";
    },
        {
        OrderDetailID = 7;
        ProductName = Oranges;
        UnitPrice = 1000;
        date = "2016-06-13T22:15:47.107";
    }
)

提取的UnitPrice輸出(仍未完全提取):

2016-07-03 22:52:21.330 T2PApp[2272:658440] Price: (
    399.99,
    1000
)

我認為您需要從數組中的對象中挖掘數據。 它與JSON無關。
有很多方法可以做到,但是沒有一種簡單的方法可以將其挖掘出來。
例如,創建一個新數組,然后遍歷目標數組,將所需的屬性放入新數組中。
基本上就是這樣。
在您的代碼中,也許下面的代碼可以工作。

NSLog(@"%@",JSON);
NSMutableArray *priceArr = [NSMutableArray array];
NSArray *arr = nil;
if ([JSON isKindOfClass:[NSArray class]]) {
    arr = (NSArray *)JSON;
    for (NSDictionary *dic in arr) {
        NSString *price = [NSString stringWithFormat:@"%@",[dic valueForKey:@"UnitPrice"]];
        price= [price stringByReplacingOccurrencesOfString:@"\"" withString:@""];
        [priceArr addObject:price];
    }
}

priceArr是您所需要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM