user5792975 user5792975 - 5 months ago 24
Objective-C Question

Objective C Accessing Elements

I'm attempting to obtain elements extracted from a dictionary and convert them to doubles. The data is being pulled from JSON and seems to be extracted into a type of array (not sure which type). Is there a way to obtain the numbers listed below individually out of the array? Please let me know if you need more information.

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);
}


Log (UnitPrice values I need individually extracted):

Dictionary output:

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";
}
)


Extracted UnitPrice output (still not completely extracted):

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

Answer

I think what you need is digging out the data from the objects in array. It not about the JSON.
There is many way to do it, but not one simply way to dig it out.
For example, create a new array, and traverse the target array, put the property you need into the new array.
It is basically like that.
In your code, maybe the code below will work.

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 is what you need.