Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting NSString to NSDictionary / JSON

I have the following data saved as an NSString :

 {
    Key = ID;
    Value =         {
        Content = 268;
        Type = Text;
    };
},
    {
    Key = ContractTemplateId;
    Value =         {
        Content = 65;
        Type = Text;
    };
},

I want to convert this data to an NSDictionary containing the key value pairs.

I am trying first to convert the NSString to a JSON objects as follows :

 NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

However when I try :

NSString * test = [json objectForKey:@"ID"];
NSLog(@"TEST IS %@", test);

I receive the value as NULL.

Can anyone suggest what is the problem ?

like image 727
GuybrushThreepwood Avatar asked Sep 11 '13 08:09

GuybrushThreepwood


2 Answers

I believe you are misinterpreting the JSON format for key values. You should store your string as

NSString *jsonString = @"{\"ID\":{\"Content\":268,\"type\":\"text\"},\"ContractTemplateID\":{\"Content\":65,\"type\":\"text\"}}";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

Now if you do following NSLog statement

NSLog(@"%@",[json objectForKey:@"ID"]);

Result would be another NSDictionary.

{
    Content = 268;
    type = text;
}

Hope this helps to get clear understanding.

like image 66
Janak Nirmal Avatar answered Oct 24 '22 15:10

Janak Nirmal


I think you get the array from response so you have to assign response to array.

NSError *err = nil;
NSArray *array = [NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
NSDictionary *dictionary = [array objectAtIndex:0];
NSString *test = [dictionary objectForKey:@"ID"];
NSLog(@"Test is %@",test);
like image 14
MobileDev Avatar answered Oct 24 '22 14:10

MobileDev