Trying to parse this JSON object in objective-C and creating an NSArray with these objects.
The first value is a counter and is specific for the object. All other values are unique.
{ "myData": [
["1","1","110","dollar","8.0","2.8","0.1","11.6"],
["2","1","110","euro","4.0","3.2","1.5","4.4"],
["3","1","120","rupier","6.0","2.9","1.3","10.8"],
["4","1","120","dinero","4.0","3.3","1.5","4.4"],
["5","2","130","drahmer","8.0","2.9","1.3","11.2"],
] }
Tried this code:
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:myData
options:kNilOptions
error:&error];
NSArray *currencyInformation = [json objectForKey:#"myData"];
But the objects are not there. Though the count of the array is 5.
Each object in the array is an array itself, so:
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:myData
options:kNilOptions
error:&error];
NSArray *currencyInformation = [json objectForKey:#"myData"];
for (NSArray *info in currencyInformation) {
// Then access each "column" with [info objectAtIndex:0,1,2,3,...]
}
In this data structure you would need to access things by index e.g
for (NSArray *currency in currencyInformation) {
NSLog(#"Currency: %#", [currency objectAtIndex:3]);
}
If you want to access things by key then you would need to change your JSON to use an array of objects instead of an array of arrays. Something like this:
{
"myData": [
{
"primaryKey" : 1,
"currency" : "dollar",
<other keys + values>...
},
]
}
In which case you could now do something like:
for (NSDictionary *currency in currencyInformation) {
NSLog(#"Currency: %#", [currency valueForKey:#"currency"]);
}
Related
I receive this JSON string from a web process
{
"result":"ok",
"description":"",
"err_data":"",
"data":[
{
"id":"14D19A9B-3D65-4FE2-9ACE-4C2D708DAAD8"
},
{
"id":"8BFD10B8-F5FD-4CEE-A307-FE4382A0A7FD"
}
]
}
and when I use the following to get the data:
NSError *jsonError = nil;
NSData *objectData = [ret dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json= [NSJSONSerialization JSONObjectWithData: objectData options:kNilOptions error: &jsonError];
NSLog(#"data: %#",[json objectForKey:#"data"]);
it gets logged as:
(
{
id = "14D19A9B-3D65-4FE2-9ACE-4C2D708DAAD8";
},
{
id = "8BFD10B8-F5FD-4CEE-A307-FE4382A0A7FD";
}
)
How can I parse the data as an NSDictionary with value and keys?
The web returns an object that has a property which is an array of objects, so...
NSDictionary *json= // your code
NSArray *array = json[#"data"];
for (NSDictionary *element in array) {
NSLog(#"%#", element);
// or, digging a little deeper
NSString *idString = element[#"id"];
NSLog(#"id=%#", idString);
}
I am trying to iterate trough a JSON array to get both the item key and value.
This is my JSON array:
{
"ClientData": [{
"Name": "Michael"
}, {
"Last": "Ortiz"
}, {
"Phone": "5555555555"
}, {
"email": "test#gmail.com"
}],
"ClientAccess": [{
"T-Shirt": "YES"
}, {
"Meals": "NO"
}, {
"VIP": "YES"
}, {
"Registration Completed": "Pending"
}]
}
Now, I am trying to iterate through the "ClientData" array, but for some reason the app is crashing with this exception:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKey:]: unrecognized selector sent to instance
This is the code I am using to iterate through the JSON array:
NSDictionary* object = [NSJSONSerialization JSONObjectWithData:JSONData options:kNilOptions error:nil];
// Client Profile Data
NSDictionary *clientDataDict = [object objectForKey:#"ClientData"];
for (id item in clientDataDict)
{
[JSONUserData addObject:[clientDataDict objectForKey:item]];
}
This code was working fine when I didn't have each item on the JSON array placed inside an array. I did this to keep a consecutive order on the array.
Can someone give me any pointers on what the problem is?
Thank you!
ClientData is an array – represented by the square brackets [] – containing dictionaries with one key/value pair respectively (a quite cumbersome structure).
NSDictionary* object = [NSJSONSerialization JSONObjectWithData:JSONData options:kNilOptions error:nil];
// Client Profile Data
NSArray *clientDataArray = [object objectForKey:#"ClientData"];
for (NSDictionary *dict in clientDataArray) {
for (NSString *key in dict) {
[JSONUserData addObject:[dict objectForKey:key]];
}
}
According to your JSON strings, it looks like that ClientData pairs with an array and each item in array is a dictionary. Therefore, revised codes will look like:
NSMutableDictionary *mDict = [NSMutableDictionary new];
NSArray *array = [object objectForKey:#"ClientData"];
for (NSDictionary *item in array) {
[mDict addEntriesFromDictionary:item];
}
I'm trying to take out the "lasttradeprice" in https://www.allcrypt.com/api.php?method=singlemarketdata&marketid=672 but I can't seem to figure out how to grab the "lasttradeprice" piece.
How would I 'filter' the "price" out? None of the other information is relevant.
Current Code:
NSURL * url=[NSURL URLWithString:#"https://www.allcrypt.com/api.php?method=singlemarketdata&marketid=672"]; // pass your URL Here.
NSData * data=[NSData dataWithContentsOfURL:url];
NSError * error;
NSMutableDictionary * json = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];
NSLog(#"%#",json);
NSMutableArray * referanceArray=[[NSMutableArray alloc]init];
NSMutableArray * periodArray=[[NSMutableArray alloc]init];
NSArray * responseArr = json[#"lasttradeprice"];
for(NSDictionary * dict in responseArr)
{
[referanceArray addObject:[dict valueForKey:#"lasttradeprice"]];
[periodArray addObject:[dict valueForKey:#"lasttradeprice"]];
}
NSLog(#"%#",referanceArray);
NSLog(#"%#",periodArray);
NOTE: Keep in mind I've never worked with JSON before so please keep your answers dumbed down a tad.
Key value coding provides an easy way to dig through that data. Use the key path for the values you want. For example, it looks like you could get the array of recent trades using the path "return.markets.OMC.recenttrades" like this (assuming your code to get the json dictionary):
NSArray *trades = [json valueForKeyPath:#"return.markets.OMC.recenttrades"];
That's a lot more concise than having to dig down one level at a time.
The value returned for a given key by an array is the array of values returned by the array's members for that key. In other words, you can do this:
NSArray *recentprices = [trades valueForKey:#"price"];
And since that's just the next step in the key path, you can combine the two operations above into one:
NSArray *recentprices = [json valueforKeyPath:#"return.markets.OMC.recenttrades.price"];
The only down side here is that there's no real error checking -- either the data matches your expectations and you get back your array of prices, or it doesn't match at some level and you get nil. That's fine in some cases, not so much in others.
Putting that together with the relevant part of your code, we get:
NSURL *url = [NSURL URLWithString:#"https://www.allcrypt.com/api.php?method=singlemarketdata&marketid=672"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error = nil;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error:&error];
NSArray *recentprices = [json valueforKeyPath:#"return.markets.OMC.recenttrades.price"];
Update: I just noticed that you want the "lasttradeprice", not the array of prices. Given that, the key path to use is simply #"return.markets.OMC.lasttradeprice", and the value you'll get back will be a string. So replace the last line above with:
NSString *lastTradePrice = [json valueforKeyPath:#"return.markets.OMC.lasttradeprice"];
The value you want is buried a few dictionaries deep. One general idea might be to dig recursively, something like this:
- (BOOL)isCollection:(id)object {
return [object isKindOfClass:[NSArray self]] || [object isKindOfClass:[NSDictionary self]];
}
- (void)valuesForDeepKey:(id)key in:(id)collection results:(NSMutableArray *)results {
if ([collection isKindOfClass:[NSDictionary self]]) {
NSDictionary *dictionary = (NSDictionary *)collection;
if (dictionary[key]) [results addObject:dictionary[key]];
for (id deeperKey in [dictionary allKeys]) {
if ([self isCollection:dictionary[deeperKey]]) {
[self valuesForDeepKey:key in:dictionary[deeperKey] results:results];
}
}
} else if ([collection isKindOfClass:[NSArray self]]) {
NSArray *array = (NSArray *)collection;
for (id object in array) {
if ([self isCollection:object]) {
[self valuesForDeepKey:key in:object results:results];
}
}
}
}
Then call it like this:
NSMutableArray *a = [NSMutableArray array];
[self valuesForDeepKey:#"lasttradeprice" in:json results:a];
NSLog(#"%#", a);
I have some NSMutableDictionary that is made from Json file.
NSMutableDictionary *result=//from json string
than , i need to edit that result ,which is built like :
{
slots = (
{
capacity = 1;
slot = sybIWQGDWw;
taken = (
"11:45-12:45",
"12:45-17:45"
);
},
{
capacity = 1;
slot = WNySjEZAmU;
taken = (
"12:00-13:00",
"13:00-18:00"
);
}
);
}
To get array of all fields i have :
NSMutableArray *slots=[result objectForKey:#"slots"];
than i get all dictionaries with :
for(NSMutableDictionary *dic in slots)
[dic setObject:#"1" forKey:#"slot"];//crash probably because i edit in for loop
Now i get crash when trying to change a field in the for loop.
How can i change a certain field ?
EDIT
This is how i make the dictionary from json (which is than mutable copy to result! )
-(NSDictionary*)getDictionaryForJsonWithString:(NSString*)string
{
NSString *dataString=string;
NSData *myData=[dataString dataUsingEncoding:NSASCIIStringEncoding];
NSError *error;
NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:myData options:kNilOptions error:&error];
//NSLog(#"getDictionaryForJsonWithString: data is: %#",dataDic);
return dataDic;
}
NSMutableDictionary *result=[[self getDictionaryForJsonWithString:json] mutableCopy];
When you create the dictionary from JSON, you need to set the option to create mutable instances, and it should probably be for both containers and leaves:
option: NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves
NSMutableArray *slots=[[result objectForKey:#"slots"] mutableCopy];
how to handle a json object with a sub object in the string. Here is an example
[{"_id":"1","Title":"Pineapple","Description":"Dole Pineapple","Icon":"icon.png","Actions":{"ACTION_PHOTO":"coupon.png", "ACTION_LINK":"google.com"}}]
How do you parse the second json "Actions" ?
What you have here is an array of dictionaries (with 1 entry), where one of the entries in the top level dictionary is also a dictionary. So you might have something like this to parse it:
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error: &e];
if (jsonArray) {
NSDictionary *dictActions;
for (NSDictionary *dict in jsonArray) {
dictActions = [dict objectForKey:#"Actions"];
NSLog(#"The action link is: %#", [dictActions objectForKey#"ACTION_LINK"]);
}
} else {
NSLog(#"Error parsing JSON: %#", [e localizedDescription]);
}