JSON string from NSMutableDictionary - - objective-c

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

Related

How to format brackets of nested JSON

I'm trying to create a string which holds JSON data. I'm having an issue formatting the inner nested data, it currently has square brackets '[]' and I'm trying to change it to '{}', so it is valid JSON. Are there better approaches/solutions to parsing this data?
Actual Results:
[
[
"eventtime":"2019-09-20 09:52:47",
"keyid":"15",
],
[
"eventtime":"2019-09-20 09:52:47",
"keyid":"15",
]
]
Desired Results
[
{
"eventtime":"2019-09-20 09:52:47",
"keyid":"15",
},
{
"eventtime":"2019-09-20 09:52:47",
"keyid":"15",
}
]
Code
// Parse and loop through the JSON
for (NSDictionary * dataDict in eventArray) {
NSMutableArray *array = [[NSMutableArray alloc] init];
eventTime = [NSString stringWithFormat:#"%#%#",#"eventtime\":\"",[self eventTimeConversion:[dataDict objectForKey:#"event_time"]]];
keyID = [NSString stringWithFormat:#"%#%#",#"keyid\":\"",[dataDict objectForKey:#"key_id"]];
editTime = [NSString stringWithFormat:#"%#%#",#"edittime\":\"",[self eventTimeConversion:[dataDict objectForKey:#"event_time"]]];
projectID = [NSString stringWithFormat:#"%#%#",#"projectid\":\"",[gotHeaders objectAtIndex:0]];
lockID = [NSString stringWithFormat:#"%#%#",#"doorid\":\"",[dataDict objectForKey:#"lock_id"]];
eventType = [NSString stringWithFormat:#"%#%#",#"eventid\":\"",[dataDict objectForKey:#"event_type"]];
[array addObject:eventTime];
[array addObject:keyID];
[array addObject:editTime];
[array addObject:projectID];
[array addObject:lockID];
[array addObject:eventType];
[event_array addObject:array];
}
}
NSData *jsonnData = [NSJSONSerialization dataWithJSONObject:event_array options:NSJSONWritingPrettyPrinted error:&error];
NSString *eventsString = [[NSString alloc] initWithData:jsonnData encoding:NSUTF8StringEncoding];
Don't create a JSON string manually, create dictionaries, this is a simplified example for the keys eventtime and keyid
The code uses modern Objective-C syntax (introduced at least 6 years ago)
NSMutableArray *array = [[NSMutableArray alloc] init];
for (NSDictionary * dataDict in eventArray) {
NSString *eventTime = [self eventTimeConversion: dataDict[#"event_time"]];
NSString *keyID = dataDict[#"key_id"];
[array addObject:#{#"eventtime":eventTime, #"keyid":keyID}];
}
NSError *error;
NSData *jsonnData = [NSJSONSerialization dataWithJSONObject: array options:NSJSONWritingPrettyPrinted error:&error];
NSString *eventsString = [[NSString alloc] initWithData:jsonnData encoding:NSUTF8StringEncoding];
Instead of using an array to store the JSON id and value parameters, use a NSDictionary:
NSDictionary *d1 = [NSDictionary dictionaryWithObjectsAndKeys:
#"eventtime", #"2019-09-20 09:52:47",
#"keyid", #"15", nil];
[event_array addObject:d1];
...
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:event_array
options:NSJSONWritingPrettyPrinted error:&error];
NSString *eventsString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"%#", eventsString);
You will need to obviously replace the hardcoded values I have put on the dictionary in the example with your values.
This will output:
[
{
"eventtime":"2019-09-20 09:52:47",
"keyid":"15",
},
{
"eventtime":"2019-09-20 09:52:47",
"keyid":"15",
}
]

create a dictionary with an array of dictionaries

Noob here. I recently started working with objective C, and currently I am stuck with dictionary concept. I want to create a json object as shown below:
{"UserData": {
"Name": Mike Smith,
"Age": 32,
"category": [1,2,3],
"Weekly Data": [
{"Monday" : [1.0,2.0,3.0]},
{"Tuesday": [1.0,2.0,3.0]}
]
}
}
I wrote the following piece of code which doesn't give the desired result. I wonder if someone could help me.
-(NSString*)populateUserPreferences
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
NSMutableArray *categorydata = [[NSMutableArray alloc] init];
NSMutableArray *weeklydata = [[NSMutableArray alloc] init];
for (int i=0;i<4; i++)
{
[categorydata addObject:[NSNumber numberWithInt:i]];
}
NSMutableArray *mondaydata = [[NSMutableArray alloc] init];
for (int j=0; j<3; j++)
{
[mondaydata addObject:[NSNumber numberWithInt:j]];
}
NSMutableArray *tuesdaydata = [[NSMutableArray alloc] init];
for (int j=0; j<3; j++)
{
[tuesdaydata addObject:[NSNumber numberWithInt:j]];
}
NSDictionary *monday = [NSDictionary dictionaryWithObject:mondaydata];
NSDictionary *tuesday = [NSDictionary dictionaryWithObject:tuesdaydata];
[weeklydata addObject: monday ];
[weeklydata addObject: tuesday ];
}
[dict setObject:[NSString stringWithFormat:"Mike Smith"] forKey:#"Name"];
[dict setObject:[NSNumber numberWithInteger:32.0] forKey:#"Age"];
[dict setObject:categorydata forKey:#"category"];
[dict setObject:weeklydata forKey:#"Weekly Data"];
NSString * userdata = [dict JSONRepresentation];
NSLog(request);
NSDictionary *userdataJson = [NSDictionary dictionaryWithObject:dict forKey:#"userData"];
return [userdataJson JSONRepresentation];
}
Thanks in advance for looking into it.
Apoorva
The mistake is when creating the monday and tuesday dictionary.
// mondaydata & tuesday is just array.
NSDictionary *monday = [NSDictionary dictionaryWithObject:mondaydata];
NSDictionary *tuesday = [NSDictionary dictionaryWithObject:tuesdaydata];
This code is mistake since you did not assign the dictionary properly (where is the key for the dictionary?). Instead you should do:
NSDictionary *mondayDict = [[NSDictionary alloc] init];
[mondayDict setObject:mondaydata forKey:"Monday"];
NSDictionary *tuesdayDict = [[NSDictionary alloc] init];
[tuesdayDict setObject:tuesdaydata forKey:"Tuesday"];
Then you can add mondayDict and tuesdayDict to your array weeklydata.
ps. just a note, name your variable meaningfully. For example, mondaydata is not descriptive enough. You should use mondayArr for example. To easily identify it is an array. Just a normal coding practice to share.
NSDictionary * dict = #{#"UserData": #{
#"Name": #"Mike Smith",
#"Age": #32,
#"category": #[#1,#2,#3],
#"Weekly Data": #[
#{#"Monday" : #[#1.0,#2.0,#3.0]},
#{#"Tuesday": #[#1.0,#2.0,#3.0]}
]
}
};
NSError * error = nil;
NSData * data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
if (error) {
NSLog(#"%#", [error localizedDescription]);
} else {
// Do what you want
}

Change json format in NSDictionary (Objective C)

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

NSDictionary inside NSMutableArray (iOS)

NSArray *arrayBlockData = [data objectForKey:kData];
for (NSDictionary *dictTicket in arrayBlockData) {
NSString *blockId = [dictTicket objectForKey:#"block_id"];
[dictJson setObject:blockId forKey:#"block_id"];
[self.arrblockIds addObject:[dictTicket objectForKey:#"block_id"]];
}
[arrkeysAndValues addObject:dictJson];
NSLog(#"arrkeysAndValues %#",arrkeysAndValues);
reponse is :
arrKeysValues (
{
"block_id" = 624;
},
{
"block_id" = 624;
},
it should be :
arrKeysValues (
{
"block_id" = 623;
},
{
"block_id" = 624;
}
Your question isn't clear. But the code sample on how you put NSDictionary inside NSMutableArray is
NSMutableDictionary *dict = [NSMutableDictionary new];
[dict setValue:#623 forKey:#"block_id"];
NSMutableDictionary *dict2 = [NSMutableDictionary new];
[dict2 setValue:#624 forKey:#"block_id"];
NSMutableArray *newArray = [NSMutableArray new];
[newArray addObject:dict];
[newArray addObject:dict2];
NSLog(#"%#", newArray);

formatting dictionary values

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