i need to send data to server with NSDictionary. The data will be name, gender dll, is coming from text field. I know i can save one dictionary like this.
NSDictionary * = #{#"employee": #"EmpA",
#"gender":#"Male",
#"pob":#"SF",
#"age":#"27",
};
But i need to add multiple data because i have button that can repeat the form procedure. After that i will send the whole data to server based on format below.
"employee": [{
"name": "EmpA",
"gender": "Male",
"pob": "SF",
"age": 27
}, {
"name": "EmpB",
"gender": "Female",
"pob": "TX",
"age": 36
}]
How i can dynamically append the dictionary?
Thanks
Use an Array of dictionaries :
NSMutableArray *employees= [[NSMutableArray alloc] init];
for(//loop through the forms) {
NSDictionary *emp = #{#"name": #"EmpA",
#"gender":#"Male",
#"pob":#"SF",
#"age":#"27",
};
[employees addObject:emp];
}
NSDictionary *payload = #{#"employee": employees};
I dont have a mac at hand so forgive any syntax errors.
You need to create an array of dictionaries and insert it in your "employee" key. Something like this should work:
NSMutableDictionary *employee = [[NSMutableDictionary alloc]init];
NSMutableDictionary *emplyeeA = [#{#"name": #"EmpA", #"gender": #"Male", #"pob": #"SF", #"age": #"27"} mutableCopy];
NSMutableDictionary *emplyeeB = [#{#"name": #"EmpB", #"gender": #"Female", #"pob": #"TX", #"age": #"36"} mutableCopy];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
[tempArray addObject: emplyeeA];
[tempArray addObject: emplyeeB];
[employee setObject:tempArray forKey:#"employee"];
Related
I am new in ios programming. I should apply data to the chart. But the framework(ShinobiControls) which I use accepts only json with certain format. So I have to change my json data format to appropriate. I have NSDictionary which contain json like this:
"data": [
"01.01.2015",
"01.01.2015",
"01.01.2015",
"01.01.2015"]
"close": [
[
1,
1,
1,
1]
And now I should change format of the json like this:
[
{
"date": "01.01.2015",
"close": 1
},
{
"date": "01.01.2015",
"close": 1
},
{
"date": "01.01.2015",
"close": 1
},
{
"date": "01.01.2015",
"close": 1
}
]
I did some manipulation with converting NSDictionary to NSArray, but didn't get anything. How can I do it? Do you have any ideas? Thank you.
So if i understand your question right, you have a dictionary that contains 2 arrays and you want to convert it to an array that contains dictionaries , assuming that that the count of the arrays in the dictionary is equal, you can do the following
//This is the first array in your dictionary
NSArray * dataArr = [data objectForKey:#"data"] ;
//This the second array in your dictionary
NSArray * closeArr = [data objectForKey:#"close"] ;
NSUInteger dataCount = [dataArr count] ;
NSUInteger closeCount = [closeArr count] ;
//This will be your result array
NSMutableArray * newData = [NSMutableArray new] ;
//The loop condition checks that the current index is less than both the arrays
for(int i = 0 ; i<dataCount && i<closeCount ; i++)
{
NSMutableDictionary * temp = [NSMutableDictionary new] ;
NSString * dataString = [dataArr objectAtIndex:i];
NSString * closeString = [closeArr objectAtIndex:i];
[temp setObject:dataString forKey:#"date"];
[temp setObject:closeString forKey:#"close"] ;
[newData addObject:temp];
}
NSArray *Arr = [[NSArray alloc] initWithObjects:#"01.01.2015",#"01.01.2015",#"01.01.2015",#"02.01.2015", nil];
NSArray *Arr1 = [[NSArray alloc] initWithObjects:#"1",#"1",#"1",#"1", nil];
NSDictionary *Dic = [[NSDictionary alloc] initWithObjectsAndKeys:Arr,#"data",Arr1,#"close", nil];
NSLog(#"%#",Dic);
NSMutableArray *ArrM = [[NSMutableArray alloc] init];
for ( int i = 0; i<Arr.count; i++) {
NSDictionary *Dic = [[NSDictionary alloc] initWithObjectsAndKeys:Arr[i],#"data",Arr1[i],#"close", nil];
[ArrM addObject:Dic];
}
NSLog(#"%#",ArrM);
NSError * err;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:ArrM options:0 error:&err];
NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"%#",myString);
I wanted to generate a JSON string of the following format:
{
"test": {
"currency": "USD",
"gte": "100"
}
}
When I executed the following lines of code:
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
[tempArray addObject:tempDict];
[tempArray addObject:subDict];
[dict setObject:tempArray forKey:#"test"];
I retrieved this JSON string.
{
"test": [{
"currency": "USD"
}, {
"gte": "100"
}]
}
Any idea where I'm going wrong?
You must do it like this instead:
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
[tempDict setObject: #"USD" forKey: #"Currency"];
[tempDict setObject: #"100" forKey: #"gte"];
[dict setObject:tempDict forKey:#"test"];
From your current try you are adding array of dictionary to dictionary so its display like
{"test":[{"currency":"USD"},{"gte":"100"}]}
You need to add dictionary,
Try Following,
NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:
tempDict,
subDict,
nil];
NSDictionary *final=#{#"test": dict};
How about this?
NSMutableDictionary *dic = [#{} mutableCopy];
NSMutableDictionary *tempDic = [#{} mutableCopy];
tempDic[#"currency"] = #"USD";
tempDic[#"gte"] = #"100";
[dic setObject:dic forKey:#"test"];
Modern Objective-C style..
Try like this:-
NSDictionary *yourDict = #{#"test": #{#"currency": #"USD",#"gte": #"100"}};
I am needing to store values in a dictionary in the following format:
{ "UserId": 123,
"UserType": "blue",
"UserActs": [{
"ActId": 3,
"Time": 1
}, {
"ActId": 1,
"Time": 6
}]
}
I know I'll need a dictionary for the intitial values and a nested one for the UserActs but I am unsure how to store seperate values for the same keys "ActId" and "Time". How would I go about adding them in the dictionary following this format?
This is the old, long winded, way of creating that dictionary (there is a new syntax, using Objective-C literals, however they are not mutable, so I chose this method):
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:[NSNumber numberWithInt:123] forKey:#"UserId"];
[dict setObject:#"blue" forKey:#"UserType"];
NSMutableArray *acts = [[NSMutableArray alloc] init];
[acts addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:3], #"ActId",
[NSNumber numberWithInt:1], #"Time",
nil]];
[acts addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:1], #"ActId",
[NSNumber numberWithInt:6], #"Time",
nil]];
[dict setObject:acts forKey:#"UserActs"];
You can also use the shorthand for arrays and dictionaries
NSDictionary * dictionary = #{ #"UserId": #123,
#"UserType": #"blue",
#"UserActs": #[#{
#"ActId": #3,
#"Time": #1
}, #{
#"ActId": #1,
#"Time": #6
}]
};
NSArray has ItemObject's in it. This ItemObject's are not grouped based on ItemID
The Sample of the json is displayed below:
You will note the itemIDs "a123","a124". There can be n number of itemIDs.
[
{
"ItemName": "John",
"ItemID": "a123"
},
{
"ItemName": "Mary",
"ItemID": "a124"
},
{
"ItemName": "Larry",
"ItemID": "a123"
},
{
"ItemName": "Michel",
"ItemID": "a123"
},
{
"ItemName": "Jay",
"ItemID": "a124"
}
]
The above response is stored in NSArray as follows:
NSMutableArray *itemArray=[[NSMutableArray alloc] init];
ItemObject *obj=[[ItemObject alloc] init];
obj.itemName=#"John";
obj.itemID=#"a123";
[itemArray addObject:obj]
.....
ItemObject *objN=[[ItemObject alloc] init];
objN.itemName=#"Jay";
objN.itemID=#"a124";
[itemArray addObject:objN].
This shows, if there are N items in JSON, then it will create a array of N items.
The above item is displayed correctly in UItableView.
Now, if want to sort them and put them in NSMutableArray group wise what will be optimal way to code it, with less memory footprint to be consumed. [i.e sorting + grouping]
I am trying to achieve the below:
NSMutableArray *itemArray=[[NSMutableArray alloc] init];
at index 0: NSArray with itemID "a123"
at index 1: NSArray with itemID "a124"
Since, available ItemIds, are dynamic, as I explained there can be "N" number of itemId's.
Step 1:
So, I first need to find the available itemId's.
Step 2:
NSMutableArray *myArray=[[NSMutableArray alloc] init];
for(NSString *itemID in itemIDS){
NSArray *itemsForID=[itemArray filterUsingPredicate:[NSPredicate predicateWithFormat:"itemID MATCHES %#",itemID]];
[myArray addObject:itemsForID];
}
myArray is the expected result.
But using filterUsingPredicate "N" number of times will be time and memory consuming.
Any, help Appreciated.
Can you please try the below code?
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:#"itemID" ascending:YES];
[itemArray sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
You could persist your data as NSManagedObjects. Then you can use an NSFetchedResultsController as data source for your table (you set a sort descriptor and a section name key path to it):
NSFetchedResultsController *controller = [[NSFetchedResultsController alloc]
initWithFetchRequest:fetchRequest
managedObjectContext:context
sectionNameKeyPath:nil
cacheName:nil];
You can also set the batch size (the max number of objects taken from the DB at a time).
Hope this helps!
{
"id": "1",
"result": [
{
"Name": "John",
"Statu": "Online"
},
{
"Name": "Alex",
"Statu": "Online"
},
{
"Name": "Diaz",
"Statu": "Offline"
}
]
}
How do i extract each "car" JSON object and put it into a native object? I tried several way but i can't do that.
NSString *responseString = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
NSString *responseDict = [responseString JSONValue];
NSArray *objects = [NSArray arrayWithObjects:[responseDict valueForKeyPath:#"result.Name"],[responseDict valueForKeyPath:#"result.Statu"],nil];
NSLog(#"objects Array: %#",objects);
**==> NSLOG gives:
(
(
"John",
"Alex",
"Diaz"
),
(
"Online",
"Online",
"Offline"
)
)
NSArray *resultsArray = [responseString JSONValue];
for (NSDictionary *personDict in resultsArray)
{
NSLog(#"ihaleAdi =: %#",[carDict valueForKey:#"result.ihaleAdi"]);
NSLog(#"ihaleDurum =: %#",[carDict valueForKey:#"result.Statu"]);
}
But ıt gıves an error tooç I want to just lıst them but ı cant do thatç can anybody help me please? thank you for reading
Use an Array to capture the responseString:
NSString *responseString = [request responseString];
NSArray *array = [responseString JSONValue];
Then when you need an individual item from that array use a Dictionary:
// 0 is the index of the array you need
NSDictionary *itemDictionary = (NSDictionary *)[array objectAtIndex:0];
Given a JSON responseString that looks like this:
[{"UniqueID":111111,"DeviceName":"DeviceName1","Location":"Device1Loc","Description":"Device1Desc"},{"UniqueID":22222,"DeviceName":"DeviceName2","Location":"Device2Loc","Description":"Device2Desc"}]
You will wind up with an Array that looks like this:
myArray = (
{
Description = "Device1Desc";
DeviceName = "DeviceName1";
Location = "Device1Loc";
UniqueID = 111111;
},
{
Description = "Device2Desc";
DeviceName = "DeviceName2";
Location = "Device2Loc";
UniqueID = 222222;
}
)
And a Dictionary of index 0 that looks like this:
myDictionary = {
Description = "Device1Desc";
DeviceName = "DeviceName1";
Location = "Device1Loc";
UniqueID = 111111;
}
Sorry for any confusion and improperly instantiated object earlier. I am still a relative newbie that learned something today.