在DetailViewController中将JSON字符串转换为NSDictionary

时间:2014-12-01 11:00:14

标签: ios json uitableview nsdictionary nsdata

试图弄清楚为什么json segue从tableviewcontroller到detailviewcontroller不起作用。是否有一个NSLog来查看数据是否通过,这就是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;
        };
    }
)

然后我......

尝试将json数据转换为detailviewcontroller中的tableview。

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

但是将JSON转换为NSData,然后NSDictionary仅在NSLog中输出“null”。

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

帮助!非常感谢。

3 个答案:

答案 0 :(得分:1)

更改以下代码行
NSArray *items = [dic valueForKeyPath:@"email"];

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

如果你仍然没有使用nslog而不是更改

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

喜欢这个

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

答案 1 :(得分:0)

您好JSON无效,因此无法正常工作......

所以首先看一下JSONhttp://json.org/example

的示例

然后你可以在这里试试JSON:jsonlint.com

以下是JSON格式良好的开头:

{
"emails": {
    "9": "i",
    "10": "j",
    "11": "k",
    "12": "l"
},
"links": {
    "1": "a",
    "2": "b",
    "3": "c",
    "4": "d"
}
}

主要将=更改为:;更改为,并添加了一些"

祝你好运。

答案 2 :(得分:0)

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

有两种可能性,而且您没有显示足够的信息:

data.detail是一个NSString。在这种情况下,这行代码完全没用,因为它只是制作字符串副本的一种昂贵方式,根本不包含任何JSON。

或者data.detail是一个NSDictionary。在这种情况下,您的整个代码绝对是错误的废话,因为在这种情况下您有一个NSDictionary,尝试将其转换为代码不起作用的JSON字符串,将该字符串转换为NSData,并将NSData转换回字典,这是你开始的地方!

出于纯粹的病态好奇心,这是哪一个?

相关问题