Search code examples
iphoneobjective-cjsonnsdatatouchjson

iphone objective-c : string to NSData conversion for json deserialization


I receive json from a webservice into a NSMutableData.

That gets converted into a NSDictionary using TouchJson.

    NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:responseData error:&error];
NSString *strData = [dictionary objectForKey:@"cars"];

I then retrieve a string from a key from that dictionary.

The string looks like below

     {
        b = "http://schemas.datacontract.org/";
        car =     (
                    {
                "car_name" = "Honda Civic";
                year = 2011;
                "dealer" = "local honda dealer";
                "bought on" = {
                    nil = 1;
                };
                "license_number" = 1234567;
                status = ReadyToGo;
            }
)};

Essentially there can be 'n' records against the 'car' key.

when I try to convert the above to NSData using

NSData *jsonData = [strData dataUsingEncoding:NSUTF8StringEncoding];

and also

NSData *jsonData = [strData dataUsingEncoding:[NSString defaultCStringEncoding]];

but I get

[__NSCFDictionary dataUsingEncoding:]: unrecognized selector sent to instance 0x532bb70

I have tried a few other encodings available and xcode still threw up.

How can I figure out the encoding being used?

This is my first attempt at deserealizing json in objective-c.

What am I missing/doing wrong here?

Thanks


Solution

  • I think it's not a string at all....

    change to this and test....

    NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:responseData error:&error];
    NSDictionary *carsDictionary = [dictionary objectForKey:@"cars"];
    NSArray *arrayOfCarDictionaries = [carsDictionary objectForKey:@"car"];