convert NSDictionary to NSString

IphoneIosNsstringNsdictionary

Iphone Problem Overview


I am trying to put the content of an NSDictionary into an NSString for testing, But have no idea how to achieve this. Is it possible? if so how would one do such a thing?

The reason I am doing this, Is I need to check the content of a NSDicitonary without the debugger running on my device. as I have to delete the running app from multitasking bar of the ios so I can see if the values I am saving into the dictionary are still available afterwards.

Iphone Solutions


Solution 1 - Iphone

You can call [aDictionary description], or anywhere you would need a format string, just use %@ to stand in for the dictionary:

[NSString stringWithFormat:@"my dictionary is %@", aDictionary];

or

NSLog(@"My dictionary is %@", aDictionary);

Solution 2 - Iphone

Above Solutions will only convert dictionary into string but you can't convert back that string to dictionary. For that it is the better way.

Convert to String

NSError * err;
NSData * jsonData = [NSJSONSerialization  dataWithJSONObject:yourDictionary options:0 error:&err];
NSString * myString = [[NSString alloc] initWithData:jsonData   encoding:NSUTF8StringEncoding];
NSLog(@"%@",myString);

Convert Back to Dictionary

NSError * err;
NSData *data =[myString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary * response;
if(data!=nil){
 response = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
}

Solution 3 - Iphone

You can use the description method inherited by NSDictionary from NSObject, or write a custom method that formats NSDictionary to your liking.

Solution 4 - Iphone

if you like to use for URLRequest httpBody

extension Dictionary {
    
    func toString() -> String? {
        return (self.compactMap({ (key, value) -> String in
            return "\(key)=\(value)"
        }) as Array).joined(separator: "&")
    }
    
}

// print: Fields=sdad&ServiceId=1222

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionC.JohnsView Question on Stackoverflow
Solution 1 - IphoneJay WardellView Answer on Stackoverflow
Solution 2 - IphoneDanial HussainView Answer on Stackoverflow
Solution 3 - IphoneSergey KalinichenkoView Answer on Stackoverflow
Solution 4 - IphoneAli OzkaraView Answer on Stackoverflow