j.TK
j.TK

Reputation: 223

Nsdictionary Format issue

I have the following answer(from server) in following format for Answer column in database.enter image description here

On updating the answer at app side and on saving it to database, it gets modified to the below format.(i.e, : is replaced by =) I would like to maintain the same format. Could someone let me know what is the issue? am using NSDictionary for accessing key value pair and am assigning final nsdictionary to DB. enter image description here

Upvotes: 0

Views: 192

Answers (3)

doxsi
doxsi

Reputation: 1014

The trick is to have a NSJSONSerialization before passing it to NSSTRING

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:YOUR_OBJECT options:0 error:&error];


NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

Upvotes: 1

Sviatoslav Yakymiv
Sviatoslav Yakymiv

Reputation: 7935

As @Larme pointed -[NSDictionary description] does not return JSON representation of dictionary. NSArray works in similar way.

Description of NSDictionary has the following format.

{
    key1 = value1;
    key2 = value2;
    ...
    keyN = valueN;
}

Description of NSArray looks as follow:

(
    object1,
    object2,
    ...
    objectN
)

In order to get JSON from dictionary you should use NSJSONSerialization(or third-party library).

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:response options:0 error:nil];
//Use line below to see formatted JSON
//NSData *jsonData = [NSJSONSerialization dataWithJSONObject:response options:NSJSONWritingPrettyPrinted error:nil]; 
NSString *string = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

Upvotes: 1

csblo
csblo

Reputation: 1631

NSDictionary and NSString containing JSON are not the same object, so they don't have the same format. When you are printing these object with an NSLog, it call the description method on theses objects. This method return the string for an NSString and a specific format string for a NSDictionary.

If you want to retrieve the JSON format, you need to transform your NSDictionary to JSON string again like following :

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
NSString *strJson = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

if (error)
    NSLog(@"An error occured");

and then :

NSLog(@"%@", strJson);

I hope my english is understandable. Don't hesitate to correct me.

Upvotes: 1

Related Questions