SMS
SMS

Reputation: 558

How to set NSString value to NSMutable dictionary?

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

Upvotes: 0

Views: 650

Answers (1)

Michael
Michael

Reputation: 6899

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

Upvotes: 1

Related Questions