How to set NSString value to NSMutable dictionary? - ios

I am implementing web-service APIs, data content type is of JSON. The body of the request should be in a string format i.e in double quotes but when I set it in a dictionary, I get the below result. Could anyone help me to set the NSString as string value in dictionary.
NSMutableDictionary *reqParams = [NSMutableDictionary new];
[reqParams setObject:#"Data.SourceStreamRequest"forKey:#"_type"];
NSMutableDictionary *reqParams1 = [NSMutableDictionary new];
[reqParams1 setObject:#"newmjpegdataSession"forKey:#"_type"];
NSLog(#"%#:%#",reqParams,reqParams1);
Output
{
"_type" = "Data.SourceStreamRequest";
}:{
"_type" = newmjpegdataSession;
}
Could anyone help me to figure out the reason why ,the dictionary values are shown with double quotes and without double quotes.
Thank you

Use NSJSONSerialization to serialize your dictionary. Try this:
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"_type", #"Data.SourceStreamRequest",
#"_type", #"newmjpegdataSession", nil];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONWritingPrettyPrinted error:&error];
NSString *resultAsString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"json:\n%#", resultAsString);
Output:
json: { "newmjpegdataSession" : "_type", "Data.SourceStreamRequest"
: "_type" }

Related

Get values from NSDictionary

Hi I'm new to iOS development. I want to get response and add those values to variable.
I tried it but I'm getting below response. I don't understand why there is slashes in this response.
#"[{\"VisitorID\":\"2864983a-e26b-441a-aedf-84e2a1770b8e\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kanasalingam\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]},{\"VisitorID\":\"133bc108-b3bf-468a-9397-e1b0dba449db\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kumar\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]}]"
I tried this :
- (void) sendOtherActiveChats:(NSDictionary *) chatDetails{
NSLog(#"inside sendOtherActiveChats");
NSLog(#"otherDetails Dictionary : %# ", chatDetails);
NSString *VisitorID = [chatDetails objectForKey:#"VisitorID"];
NSString *ProfileID = [chatDetails objectForKey:#"ProfileID"];
NSString *CompanyID = [chatDetails objectForKey:#"CompanyID"];
NSString *VisitorName = [chatDetails objectForKey:#"VisitorName"];
NSString *OperatorName = [chatDetails objectForKey:#"OperatorName"];
NSString *isocode = [chatDetails objectForKey:#"isocode"];
NSLog(#"------------------------Other Active Chats -----------------------------------");
NSLog(#"VisitorID : %#" , VisitorID);
NSLog(#"ProfileID : %#" , ProfileID);
NSLog(#"CompanyID : %#" , CompanyID);
NSLog(#"VisitorName : %#" , VisitorName);
NSLog(#"OperatorName : %#" , OperatorName);
NSLog(#"countryCode: %#" , isocode);
NSLog(#"------------------------------------------------------------------------------");
}
Can some one help me to get the values out of this string ?
You are getting Array of Dictionary in response, but your response is in string so you convert it to NSArray using NSJSONSerialization like this way for that convert your response string to NSData and after that use that data with JSONObjectWithData: to get array from it.
NSString *jsonString = #"[{\"VisitorID\":\"2864983a-e26b-441a-aedf-84e2a1770b8e\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kanasalingam\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]},{\"VisitorID\":\"133bc108-b3bf-468a-9397-e1b0dba449db\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kumar\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]}]";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&e];
Now loop through the array and access the each dictionary from it.
for (NSDictionary *dic in jsonArray) {
NSLog(#"%#",[dic objectForKey:#"VisitorID"]);
... and so on.
}
First you need to parse your string.
NSString *aString = #"[{\"VisitorID\":\"2864983a-e26b-441a-aedf-84e2a1770b8e\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kanasalingam\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]},{\"VisitorID\":\"133bc108-b3bf-468a-9397-e1b0dba449db\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kumar\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]}]";
NSData *data = [aString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#",[[json objectAtIndex:0] objectForKey:#"VisitorID"]);
So you have JSON string and array of 2 objects. So write following code
This will convert JSON string to Array
NSData *myJSONData = [YOUR_JSON_STRING dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSMutableArray *arrayResponse = [NSJSONSerialization JSONObjectWithData:myJSONData options:NSJSONReadingMutableContainers error:&error];
Now use for loop and print data as
for (int i = 0; i < arrayResponse.count; i++) {
NSDictionary *dictionaryTemp = [arrayResponse objectAtIndex:i];
NSLog(#"VisitorID : %#",[dictionaryTemp valueForKey:#"VisitorID"]);
NSLog(#"ProfileID : %#",[dictionaryTemp valueForKey:#"ProfileID"]);
NSLog(#"CompanyID : %#",[dictionaryTemp valueForKey:#"CompanyID"]);
NSLog(#"VisitorName : %#",[dictionaryTemp valueForKey:#"VisitorName"]);
}
Now there are good chances that you will get NULL for some keys and it can cause in crash. So avoid those crash by using Null validations.

Setting data in correct JSON format using Array and Dictionary

Below is the model for which I have to set the data. I am using array and dictionary to achieve this, Here is the code which I tried. But its giving me the output which is invalid JSON.
One more thing I want to ask is why the log of an array starts and ends with small braces?
Any help would be much appreciated.
Code:
NSDictionary *paramDic = [NSDictionary dictionaryWithObjectsAndKeys:
parameterName,#"parameterName",
parameterType, #"parameterType",
[NSNumber numberWithBool:parameterSorting],#"parameterSorting",[NSNumber numberWithBool:parameterSorting],
#"parameterOrdering",
nil];
NSMutableArray *paramArray = [NSMutableArray arrayWithObject:paramDic];
NSDictionary *paramData = #{#"rqBody":#{#"catalogName":#"",#"userId":#"", #"parameter":paramArray, #"catalogMode":#""}};
NSData *postData = [NSKeyedArchiver archivedDataWithRootObject:paramData];`
Output:
{"rqBody":{"catalogName":"abcd","userId":"65265hgshg76","parameter":"(
{
parameterName = anandShankar;
parameterOrdering = 1;
parameterSorting = 1;
parameterType = Text;
}
)","catalogMode":"xxxxxx"}}
Desired Output:
{"rqBody":{"catalogName":"abcd","userId":"65265hgshg76","parameter":[{
"parameterName" : "anandShankar",
"parameterOrdering" : 1,
"parameterSorting" : 1,
"parameterType" : "Text"
}],"catalogMode":"xxxxxx"}}
There is nothing wrong in it. in console or log round braces () indicates array. if it is showing round braces then it is array. you will never het [] square braces in console or log.
Update :
NSData *data = [NSJSONSerialization dataWithJSONObject:paramData options:kNilOptions error:nil];
and then send this data to server. it will in your desired json fromat
hope this will help :)
Try this code :
NSDictionary *paramDic = [NSDictionary dictionaryWithObjectsAndKeys:
#"Object1",#"parameterName",
#"Object2", #"parameterType",
#'Object3',#"parameterSorting",#"Object4",
#"parameterOrdering",
nil];
NSMutableArray *paramArray = [NSMutableArray arrayWithObject:paramDic];
NSDictionary *paramData = #{#"rqBody":#{#"catalogName":#"",#"userId":#"", #"parameter":paramArray, #"catalogMode":#""}};
Add this lines :
NSError * err;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:paramData options:0 error:&err];
NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"%#", myString); // it will print valid json
JSON
{
"rqBody":{
"catalogName":"",
"parameter":[
{
"parameterOrdering":"Object4",
"parameterName":"Object1",
"parameterType":"Object2",
"parameterSorting":51
}
],
"userId":"",
"catalogMode":""
}
}

Converting NSString to JSON with NSJSONSerialization is not working

I have this function:
- (void)checkLogin:(NSString *)pLogin andPassword:(NSString*) pPassword {
//Create the data object.
NSMutableDictionary *tLoginAndPasword = [NSMutableDictionary dictionaryWithObjectsAndKeys:pLogin,#"Login",pPassword,#"Password", nil];
NSMutableDictionary *tData = [NSMutableDictionary dictionaryWithObjectsAndKeys:[_Util serializeDictionary:tLoginAndPasword],#"Data", nil];
//Call the login method.
NSData *tResponse = [_Util getLogin:tData];
if (tResponse != Nil) {
_oLabelErrorLogin.hidden = YES;
[_Util setUser:pLogin andPassword:pPassword];
NSMutableDictionary *tJSONResponse =[NSJSONSerialization JSONObjectWithData:tResponse options:kNilOptions error:nil];
NSString *tPayload = [tJSONResponse objectForKey:#"Payload"];
if([[tJSONResponse objectForKey:#"StatusCode"] isEqual: #"424"]) {
//Set global values.
NSData *tPayloadData = [tPayload dataUsingEncoding:NSUTF8StringEncoding];
if ([NSJSONSerialization isValidJSONObject:tPayloadData]) {
_Payload = [NSJSONSerialization JSONObjectWithData:tPayloadData options:kNilOptions error:nil];
_RowCount = _Payload.count;
} else {
NSLog(#"JSON Wrong String %#",tPayload);
}
} else if([[tJSONResponse objectForKey:#"StatusCode"] isEqual: #"200"]){
_Payload = Nil;
}
} else {
//Set global values.
_Payload = Nil;
_oLabelErrorLogin.hidden = NO;
//Clear login data.
_oLogin.text = #"";
_oPassword.text = #"";
[_Util setUser:#"" andPassword:#""];
}
}
The JSON response looks like this:
{
"Payload": "{\"UserName\":\"Marco Uzcátegui\",\"Clients\":[{\"UserProfileId\":4,\"ProfileName\":\"Platform Administrator\",\"ClientName\":\"Smart Hotel Platform\",\"InSession\":true},{\"UserProfileId\":5,\"ProfileName\":\"Administrator\",\"ClientName\":\"La Moncloa de San Lázaro\",\"InSession\":false},{\"UserProfileId\":6,\"ProfileName\":\"Administrator\",\"ClientName\":\"Jardín Tecina\",\"InSession\":false}]}",
"StatusCode": "424",
"StatusDescription": null
}
As you can see, I have a escaped string inside "Payload" that is a correct JSON, so I want to generate another NSMutableDictionary with that string, so I'm doing this:
NSData *tPayloadData = [tPayload dataUsingEncoding:NSUTF8StringEncoding];
if ([NSJSONSerialization isValidJSONObject:tPayloadData]) {
_Payload = [NSJSONSerialization JSONObjectWithData:tPayloadData options:kNilOptions error:nil];
_RowCount = _Payload.count;
} else {
NSLog(#"JSON Wrong String %#",tPayload);
}
So I'm creating an NSData from the NSString and asking if is valid, it always returns false.
I have tried to replace the "\" from the string and is not working.
[tPayload stringByReplacingOccurrencesOfString:#"\\\"" withString:#""]
I have tried to create a NSMutableDictionary with the string, but the result is not a dictionary.
NSMutableDictionary *tPayload = [tJSONResponse objectForKey:#"Payload"];
I'm kind of lost here.
Any help will be appreciated.
Regards.
The issue is this line
[NSJSONSerialization isValidJSONObject:tPayloadData]
From the documentation of isValidJSONObject
Returns a Boolean value that indicates whether a given object can be
converted to JSON data.
given object means an NSArray or NSDictionary but not NSData
Remove that check and implement the error parameter in JSONObjectWithDataoptions:error:
The method NSJSONSerialization.isValidJSONObject: checks if an object (e.g. a NSDictonary or NSArray instance) can be converted to JSON. It doesn't check if a NSData instance can be converted from JSON. For NSData, it will always return false.
So just call NSJSONSerialization.JSONObjectWithData:options: and check the result instead.

NSDictionary format

Can anybody help me create an NSDictionary format of the following structure:
{
key1 = "value1";
key2 = "value2";
key3 = [
{
key01 = "value01";
key02 = "value02";
},
{
key01 = "value01";
key02 = "value02";
},
{
key01 = "value01";
key02 = "value02";
}
];
}
Try this code it might help you.
NSDictionary *dicationary = #{
#"key1":#"value1",
#"key2":#"value2",
#"key3":#[#{#"key01":#"value01",#"key02":#"value02"},
#{#"key01":#"value01",#"key02":#"value02"},
#{#"key01":#"value01",#"key02":#"value02"}]
};
There is API in obj-c to convert Json to nsdictionary .I guess you should try that :
First convert json to nsdata (assuming you above JSON is in string format)
2.Then you API to convert that to NSDictionary :
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
Just to answer your question about converting that JSON data to NSDictionary, here it is:
(assuming you already got your JSON data)
// add the first 2 VALUES with it's KEYS
NSMutableDictionary *mainDict = [NSMutableDictionary dictionary];
[mainDict setValue:VALUE1 forKey:KEY1];
[mainDict setValue:VALUE2 forKey:KEY2];
// then for the last KEY, create a mutable array where you will store your sub dictionaries
NSMutableArray *ma = [NSMutableArray array];
NSMutableDictionary *subDict = [NSMutableDictionary dictionary];
[subDict setValue:SUB_VALUE1 forKey:SUB_KEY1];
[subDict setValue:SUB_VALUE1 forKey:SUB_KEY2];
[ma addObject:subDict];
// then add that array to your main dictionary
[mainDict setValue:ma forKey:KEY3];
// check the output
NSLog(#"mainDict : %#", mainDict);
// SAMPLE DATA - Test this if this is what you want
NSMutableDictionary *mainDict = [NSMutableDictionary dictionary];
[mainDict setValue:#"value1" forKey:#"key1"];
[mainDict setValue:#"value2" forKey:#"key2"];
NSMutableArray *ma = [NSMutableArray array];
NSMutableDictionary *subDict = [NSMutableDictionary dictionary];
[subDict setValue:#"subValue1" forKey:#"subKey1"];
[subDict setValue:#"subValue2" forKey:#"subKey2"];
[ma addObject:subDict];
[mainDict setValue:ma forKey:#"key3"];
NSLog(#"mainDict : %#", mainDict);
The following should work for you:
NSString *jsonString = #"{\"ID\":{\"Content\":268,\"type\":\"text\"}}";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#", jsonDict[#"ID"][#"Content"]);
Will return you:
268

How assign value to a JSON string?

I get this JSON object from my web service
0: {
Username: "John"
Password: "12345"
Position: "Admin"
Job: "Developer"
ResourceJobId: 1
}
When I try to assign a value, for example, to Username JSON string, I get a semantic error:
id obj = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&error];
for (NSDictionary *dictionary in array) {
NSString *usernameString = #"";
//this line of code gives me an error: Expression is not assignable
[dictionary objectForKey:#"Username"] = usernameString ;
I know how get the JSON object with NSJSONSerialization class, but my target is how assign the value #"" to the JSON object.
So how can I assign the value #"" to the Username JSON string?
While you are trying to fetched dictionary from array. it is not mutable dictionary so you need to created NSMutableDictionary while fetching data from Array. following code will help you to change username.
for (NSMutableDictionary *dictionary in array)
{
NSMutableDictionary* dictTemp = [NSMutableDictionary dictionaryWithDictionary:dictionary];
[dictTemp setObject:usernameString forKey#"Username"];
[_arrayList replaceObjectAtIndex:index withObject:dictTemp];
}
Well your assignment operation is written wrong, it should be indeed like this:
If you need to get value from dictionary
usernameString = [dictionary objectForKey:#"Username"];
If you want to set a value to your dictionary, first of all your dictionary should be NSMutableDictionary
[dictionary setObject:usernameString forKey:#"Username"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
id obj = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&error];
if(!error && [obj isKindOfClass:[NSArray class]]){
NSArray *array = (NSArray *)obj;
Booking *booking = nil;
for (NSMutableDictionary *dictionary in array) {
NSString *usernameString = #"";
//this line of code gives me an error: Expression is not assignable
[dictionary objectForKey:#"Username"] = usernameString;
Yes, is a compiler error
You need to have a mutabledictionary inorder to change the value. Try this
for (NSDictionary *dictionary in array) {
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:dictionary];
NSString *usernameString = #"";
[mutableDictionary setValue:#"" forKey:usernameString];
}
Even the answers are correct, I want to add that you do not have to do this your own. NSJSONSerialization already has a solution for that. Simply pass as options one of these:
NSJSONReadingMutableContainers = (1UL << 0),
NSJSONReadingMutableLeaves = (1UL << 1),
when reading the JSON.

Resources