Search code examples
iosjsonuitableviewnsdictionarynsdata

Converting JSON string to NSDictionary in DetailViewController


Trying to figure out why the json segue from tableviewcontroller to detailviewcontroller isn't working. Did an NSLog to see if data was pass, this is what showed up in dvc.

"data.detail" NSLog:

(
        {
        emails =         {
            10 = j;
            11 = k;
            12 = l;
            9 = i;
        };
        links =         {
            1 = a;
            2 = b;
            3 = c;
            4 = d;
        };
        location =         {
            13 = m;
            14 = n;
            15 = o;
            16 = p;
        };
        numbers =         {
            5 = e;
            6 = f;
            7 = g;
            8 = h;
        };
    }
)

Then I...

Tried to convert the json data into a tableview in the detailviewcontroller.

NSString *rawString = [NSString stringWithFormat:@"%@", data.detail];
NSString *jsonString = rawString;
NSData *JSONdata = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError = nil;

But converting JSON to NSData then NSDictionary only output "null" in NSLog.

NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:JSONdata options:0 error:&jsonError];
NSArray *items = [dic valueForKeyPath:@"email"];
NSLog(@"dic %@", dic);
NSLog(@"items %@", items);

Help! Thanks very much.


Solution

  • Change below line of code from

    NSArray *items = [dic valueForKeyPath:@"email"];
    

    to

    NSArray *items = [dic valueForKeyPath:@"emails"];
    

    if still you got nslog nil than change

    NSString *rawString = [NSString stringWithFormat:@"%@", data.detail];
    

    to like this

    NSString *rawString = @"{\"emails\" :{\"10\" : \"j\",\"11\" : \"k\",\"12\" : \"l\",\"9\" : \"i\"},\"links\" :{\"1\" : \"a\",\"2\" : \"b\",\"3\" : \"c\",\"4\" : \"d\"}}";