get value from NSDictionary not work - ios

1.I get JSON data from web services and add It's to NSDictionary
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
2.Then I Show "dic" in NSLog It's present
{"query": [{"IndexNo": 1,"ID": "01","Picture": "img/food-48.png"}]}
3.Then I get data value from "dic" in to new NSDictionary "dt"
NSDictionary *dt = [dic objectForKey: #"query"];
4.Then I Show "dt" in NSLog It's present
({ID = 01;IndexNo = 1;Picture = "img/food-48.png";})
5.I want to get "ID" from "dt". I use this code
NSString *ID = [dt objectForKey: #"ID"];
but it's error
-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x8a40a60

Can you try this
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
NSArray *arr = [dic objectForKey: #"query"];
NSDictionary *dt = arr[0];
NSString *ID = [dt objectForKey: #"ID"];

[dic objectForKey: #"query"] returns an NSArray actually. Note these square brackets in the output from the first NSLog statement:
{"query": [...]}
Try this:
NSArray *dtArray = [dic objectForKey: #"query"];
NSDictionary *dt = dtArray[0];
NSString *ID = [dt objectForKey:#"ID"];
Or to use the key-value coding behavior of NSDictionary and NSArray:
NSString *ID = [[dic valueForKeyPath:#"query.ID"] firstObject];

NSDictionary *dt = [[dic objectForKey: #"query"] objectAtIndex:0];
NSString *ID = [dt objectForKey: #"ID"];
You are trying to get value for key from array. change these lines.

From your jsonStructure
{"query": [{"IndexNo": 1,"ID": "01","Picture": "img/food-48.png"}]}
object for key "query" is an array as {} is a dictionary and [] is an array. so do the following
NSArray *tempArray = [dt objectForKey:#"query"];
NSDictionary *tempDictionary = [tempArray objectAtIndex:0];
NSString *ID = [tempDictionary objectForKey:#"ID"];
Hope this helps.

Related

NSDictionnary to NSString

I have a NSDictionary that comes like that : (
1,
2,
3
)
And I would like to assign a NSString like this: 123, how? Thank you
My code :
NSDictionary *keys = [self.json valueForKeyPath:#"survey.questions.id"][0][0];
NSString *keysString = [NSString stringWithFormat:#"my dictionary is %#", keys];
NSArray *keys = [dict allKeys];
NSString *result = [[keys valueForKey:#"description"] componentsJoinedByString:#""];

Need To Add New Keys and Values Into Plist Using Objective C? [duplicate]

This question already has answers here:
How To Add New Keys and Values Into Plist Using Objective C?
(1 answer)
Save NSDictionary to plist
(3 answers)
Closed 7 years ago.
I have created JSON data store Into Plist. Now the problem is after JSON data storage, I need to add two set of keys into every array of dictionary items like below Image_2.The key name isParent - Boolean YES and isChild - Boolean YES with levels like mentioned below Image_2.
Now I have below structure of plsit datas Its perfectly working by below code.
I need to add two keys for outside of object subjectcount and inside of objectsubjectcount red marked datas.
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:&error];
NSDictionary *response = JSON[#"response"];
NSArray *keys = [response allKeys];
NSMutableArray *objects = [NSMutableArray new];
for (NSString *key in keys) {
NSMutableDictionary *object = response[key];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"subject = %#",object[#"subject"]];
NSArray *objectsWithSameSubject = [objects filteredArrayUsingPredicate:predicate];
NSInteger subjects = [object[#"subject"] integerValue];
if (subjects > 0) {
NSMutableArray *Objects_Subjectcount = [NSMutableArray new];
[object setObject:Objects_Subjectcount forKey:#"Objects_Subjectcount"];
for (NSInteger i = 0; i < subjects; i++) {
[Objects_Subjectcount addObject:object];// object or anything you need
}
}
[objects addObject:object];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = paths.firstObject;
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"File.plist"];
NSError *writeError = nil;
NSDictionary *finalDict = #{#"Objects": objects};
NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:finalDict format:NSPropertyListXMLFormat_v1_0 options:NSPropertyListImmutable error:&writeError];
if(plistData){
[plistData writeToFile:plistPath atomically:YES];
}
else {
NSLog(#"Error in saveData: %#", error);
}
NOTE : all the datas store by JSON but after storage need to add additional values by manually! Thats I am trying
NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:finalDict format:NSPropertyListXMLFormat_v1_0 options:NSPropertyListMutable error:&writeError];
Retrieve data from plist like this.
NSMutableDictionary *plistDic = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
Now suppose you want to update first array of dictionary then
NSMutableArray *array = [[NSMutableArray alloc]init:[plistDic objectAtIndex:0]]
You can do for loop if you want to change all array data...Right i am just using first object data..
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init:[array objectAtIncex:0]];
[dict addObject:"yourdata" forKey:"yourkey"];
[array replaceObject:dict atIndex:0];
[plistDic replaceObjectAtIndex:0 withObject:array];
And last
[plistDic writeToFile:plistPath atomically:YES];
The object from response[key] is immutable so it can't be modified as below:
[object setObject:Objects_Subjectcount forKey:#"Objects_Subjectcount"];
Making it mutable as below, it can be modified by any method add/remove/set.
NSMutableDictionary *object = [response[key] mutableCopy];
Hope using below modified block, you would see required changes.
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:&error];
NSDictionary *response = JSON[#"response"];
NSArray *keys = [response allKeys];
NSMutableArray *objects = [NSMutableArray new];
for (NSString *key in keys) {
NSMutableDictionary *object = [response[key] mutableCopy];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"subject = %#",object[#"subject"]];
NSArray *objectsWithSameSubject = [objects filteredArrayUsingPredicate:predicate];
NSInteger subjects = [object[#"subject"] integerValue];
if (subjects > 0) {
[object setObject:#"" forKey:#"level"];
[object setObject:#(YES) forKey:#"isParent"];
NSMutableArray *Objects_Subjectcount = [NSMutableArray new];
for (NSInteger i = 0; i < subjects; i++) {
[Objects_Subjectcount addObject:#{#"level":#(0), #"isChild":#(YES)}];
}
[object setObject:Objects_Subjectcount forKey:#"Objects_Subjectcount"];
}
[objects addObject:object];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = paths.firstObject;
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"File.plist"];
NSError *writeError = nil;
NSDictionary *finalDict = #{#"Objects": objects};
NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:finalDict format:NSPropertyListXMLFormat_v1_0 options:NSPropertyListImmutable error:&writeError];
if(plistData){
[plistData writeToFile:plistPath atomically:YES];
}
else {
NSLog(#"Error in saveData: %#", error);
}

How to fetch NSString from a JSON array of dictionaries?

This is my JSON:
-elements: [
{
HomeworkElementSession: {
id: "608743",
name: "Interval for x",
description: "",
}
}
]
...
I was able to get to the point where I have an actual NSArray representing the "elements" node and therefore containing only one object in the array.
But I have no idea how to reach this string "name".
What i did was:
NSMutableArray *elements = [singleHomework objectForKey:#"elements"];
for(int i=0; i<elements.count; i++){
NSDictionary* homeworkSession = [elements objectAtIndex:i];
NSString* name = [homeworkSession objectForKey:#"name"];
NSLog(#"%#",name);
}
But i get nil in Log.
What am I doing wrong ?
NSMutableArray *elements = [singleHomework objectForKey:#"elements"];
for(int i=0; i<elements.count; i++){
NSDictionary* homeworkSession = [elements objectAtIndex:i];
NSDictionary* dataDict = [homeworkSession objectForKey:#"HomeworkElementSession"];
NSString* name = [dataDict objectForKey:#"name"];
NSLog(#"%#",name);
}
You need to get the Dictionary for key HomeworkElementSession first
NSMutableArray *elements = [singleHomework objectForKey:#"elements"];
for(int i=0; i<elements.count; i++){
NSDictionary* mainhomeworkSession = [elements objectAtIndex:i];
NSDictionary* homeworkSession = [mainhomeworkSession objectForKey:#"HomeworkElementSession"];
NSString* name = [homeworkSession objectForKey:#"name"];
NSLog(#"%#",name);
}
Hope it helps you..!
NSMutableArray *elements = [singleHomework objectForKey:#"elements"];
for(NSDictionary *dict in elements){
NSDictionary* dataDict = [dict objectForKey:#"HomeworkElementSession"];
NSString* name = [dataDict objectForKey:#"name"];
NSLog(#"%#",name);
}
Try this may be help full ,
Note: you are getting output in NSString so use this
NSString *singleHomework = #"your data";
NSMutableDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:[singleHomework dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:Nil];
NSMutableArray *dataArray = [dataDic valueForKey:#"elements"];
NSLog(#"Name Print %#",[dataArray[0] valueForKey:#"name"]);
First, I'm not sure why you have a hyphen in the dictionary key "-elements". That could be a problem. However, your main problem is that your JSON is an array containing a single dictionary which then contains a dictionary (HomeworkElementSession) which has attributes.
NSString * json = #"{\"elements\": [{\"HomeworkElementSession\": {\"id\": \"608743\", \"name\":\"Interval for x\", \"description\": \"\"}}]}";
NSData * jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&e];
NSLog(#"dict=%#", dict);

How choose array in JSON

I have some problem in my project. So i used JSON for take some information.
When i have JSON with folders(example: i have NSDictionary with name Playlist in this playlist i have NSString name and album) for this i make this code:
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webdata options:0 error:nil];
NSDictionary *playlist =[allDataDictionary objectForKey:#"playlist"];
for (NSDictionary *diction in playlist) {
NSDictionary *artist = [diction objectForKey:#"artist"];
NSDictionary *song = [diction objectForKey:#"song"];
NSString *name = [artist objectForKey:#"name"];
NSString *namesong = [song objectForKey:#"name"];
[array addObject:name];
[array2 addObject:namesong];
}
[[self tableTrack]reloadData];
}
It's work perfect! BUT! When i don't have any folders, only, JSON without NSDictionary only NSStrings, how make? Sorry for my stupid question but really i tried write:
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webdata options:0 error:nil];
NSString *name = [allDataDictionary objectForKey:#"name"];
NSString *namesong = [allDataDictionary objectForKey:#"name"];
[array addObject:name];
[array2 addObject:namesong];
}
[[self tableTrack]reloadData];
}
But i have error, also my app crashed:
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x7615c90'
So, what i doing wrong?
The error says you have an NSArray, not an NSDictionary. This corresponds to a JSON array:
[
{ "name" : "fred" },
{ "name" : "jane" }
]
Here you have an array of dictionaries. You may want:
NSArray *people = [NSJSONSerialization JSONObjectWithData:webdata options:0 error:nil];
for (NSDictionary *person in people) {
NSLog(#"name is %#", person[#"name"];
}

Parsing a JSON array with dictionaries

I'm having some trouble getting to the data I want to in the JSON file. Here is a shortened version of the output from my console:
{
AUD = {
15m = "125.15547";
24h = "124.74";
buy = "121.0177";
last = "125.15547";
sell = "123.44883";
symbol = "$";
};
BRL = {
15m = "120.34";
24h = "120.34";
buy = "120.34";
last = "120.34";
sell = "120.34";
symbol = "R$";
};
CAD = {
15m = "129.08612";
24h = "131.07";
buy = "128.66227";
last = "129.08612";
sell = "129.08612";
symbol = "$";
};
}
I'm trying to parse the file using the built in JSON parsing library. Here is the parser in my viewDidLoad method:
_tickerArray = [NSMutableArray array];
NSURL *tickerDataURL = [NSURL URLWithString:#"https://blockchain.info/ticker"];
NSData *jsonData = [NSData dataWithContentsOfURL:tickerDataURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#", dataDictionary);
NSArray *ar = [NSArray arrayWithObject:dataDictionary];
for (NSString *key in [dataDictionary allKeys]) {
for (NSDictionary *dict in ar) {
TickerData *t;
t.currency = [dict objectForKey:key];
t.symbol = [dict objectForKey:#"symbol"];
t.last = [dict objectForKey:#"last"];
[_tickerArray addObject:t];
}
}
I want to store the currency code (like AUD or BRL) into t.currency along with some of the other data contained in the currency dictionary but now my app is crashing.
Error code:
NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil
None of the objects seem to get added to the _tickerArray
Help?
EDIT: Getting the keys to display with the proper data populating other fields:
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#", dataDictionary);
for (NSString *key in [dataDictionary allKeys]) {
NSDictionary *dic=[dataDictionary objectForKey:key];
TickerData *t=[[TickerData alloc] init];
t.currency = key;//EDITED
t.symbol = [dic objectForKey:#"symbol"];
t.last = [dic objectForKey:#"last"];
[_tickerArray addObject:t];
}
t is nil, you have to alloc/ init it:
TickerData *t = [[TickerData alloc] init];
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#", dataDictionary);
//NSArray *ar = [NSArray arrayWithObject:dataDictionary];//REMOVED
for (NSString *key in [dataDictionary allKeys]) {
NSDictionary *dic=[dataDictionary objectForKey:key];//ADDED
for (NSString *dickey in [dic allKeys]) { //MODIFIED
NSDictionary *dict=[dic objectForKey:dicKey];//ADDED
TickerData *t=[[TickerData alloc] init];//ALLOC INIT ?
t.currency = key;//EDITED
t.symbol = [dict objectForKey:#"symbol"];
t.last = [dict objectForKey:#"last"];
[_tickerArray addObject:t];
}
}
Your data doesn't contain any array, its all dictionaries, try the above code see comments too..
Hope it works..
Edited:
Yes you have initialize the object too, as suggested above in other answers..
Try it....
NSURL *url = [NSURL URLWithString:#"https://blockchain.info/ticker"];
NSLog(#"API : %#",url);
NSMutableData *jsonData = [NSMutableData dataWithContentsOfURL:url];
NSString *data = [[NSString alloc] initWithBytes: [jsonData mutableBytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
dictionary = [data JSONValue];
NSDictionary *dict = [dictionary objectForKey:#"AUD"];
NSLog(#"%#",dict);
NSString *last = [dict valueForKey:#"last"];
NSLog(#"%#",last);

Resources