86

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 ?

tomahh
  • 13,441
  • 3
  • 49
  • 70
GuybrushThreepwood
  • 5,598
  • 9
  • 55
  • 113

5 Answers5

265

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;
}
starball
  • 20,030
  • 7
  • 43
  • 238
Janak Nirmal
  • 22,706
  • 18
  • 63
  • 99
  • 1
    Not really an answer to the question since you tell the person to reformat their string. In some cases (e.g., iOS6 format IAP receipts), you are given a string in this format. – Chris Prince Apr 06 '14 at 02:00
  • 1
    You are always free to post the answers even to the questions which has accepted answers. So please hurry and post your version of answer and approach OP to consider revising accepted answer. :) – Janak Nirmal Apr 07 '14 at 04:47
  • 1
    BTW OP has posted JSON? Are you sure about that? Please check the requirement of OP and is it possible to achieve within that format? If yes answer the question and I will upvote and will create new bounty and award it to you. – Janak Nirmal Apr 07 '14 at 04:49
14

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);
MobileDev
  • 1,024
  • 9
  • 21
6

Use this code where str is your JSON string:

NSError *err = nil;
NSArray *arr = 
 [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] 
                                 options:NSJSONReadingMutableContainers 
                                   error:&err];
// access the dictionaries
NSMutableDictionary *dict = arr[0];
for (NSMutableDictionary *dictionary in arr) {
  // do something using dictionary
}
Alex Cio
  • 6,014
  • 5
  • 44
  • 74
Woodstock
  • 22,184
  • 15
  • 80
  • 118
  • [arr count] is returning zero. – GuybrushThreepwood Sep 11 '13 at 08:38
  • ERROR is Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x1f5b3660 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.} – GuybrushThreepwood Sep 11 '13 at 08:43
  • something is malformed in your json data – Woodstock Sep 11 '13 at 08:54
2

Swift 3:

if let jsonString = styleDictionary as? String {
    let objectData = jsonString.data(using: String.Encoding.utf8)
    do {
        let json = try JSONSerialization.jsonObject(with: objectData!, options: JSONSerialization.ReadingOptions.mutableContainers) 
        print(String(describing: json)) 

    } catch {
        // Handle error
        print(error)
    }
}
Josh O'Connor
  • 4,694
  • 7
  • 54
  • 98
0

Use the following code to get the response object from the AFHTTPSessionManager failure block; then you can convert the generic type into the required data type:

id responseObject = [NSJSONSerialization JSONObjectWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] options:0 error:nil];
honk
  • 9,137
  • 11
  • 75
  • 83
krish2me
  • 9
  • 7