xcode 将 JSON 数据从 NSData 转换为 NSDictionary

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17029229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 03:28:26  来源:igfitidea点击:

Converting JSON Data from NSData to NSDictionary

iphoneiosxcodejsonipad

提问by Vishal Aggarwal

I have a PHP service that returns me the following response in NSData format. After converting the same into NSString using:

我有一个 PHP 服务,它以 NSData 格式返回以下响应。使用以下方法将其转换为 NSString 后:

NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

I get the following:

我得到以下信息:

[
    {
        "Emp_Name": "Krishna Mamidi",
        "Emp_Designation": "Driver",
        "Emp_Type": "Permanent",
        "Joining_Date": "05-MAR-2011",
        "Salary": 10000
    },
    {
        "Emp_Name": "Aditya Reddy",
        "Emp_Designation": "supervisor",
        "Emp_Type": "Permanent",
        "Joining_Date": "06-MAR-2011",
        "Salary": 9000
    },
    {
        "Emp_Name": "Rajiv krishna",
        "Emp_Designation": "director",
        "Emp_Type": "Permanent",
        "Joining_Date": "01-MAR-2011",
        "Salary": 100000
    }
]

The above is in correct JSON Format.

以上是正确的JSON格式。

Having received the NSData format of the above, I use the following to convert the same into JSON Dictionary:

收到上面的 NSData 格式后,我使用以下内容将其转换为 JSON 字典:

NSError *error = nil;
id jsonObject = [NSJSONSerialization
                 JSONObjectWithData:data
                 options:NSJSONWritingPrettyPrinted error:&error];

NSDictionary *deserializedDictionary = nil;

if (jsonObject != nil && error == nil)
{
    if ([jsonObject isKindOfClass:[NSDictionary class]])
    {
        //Convert the NSData to NSDictionary in this final step
        deserializedDictionary = (NSDictionary *)jsonObject;
    }
}

However the "deserializedDictionary" is always null or empty. Basically it never came inside the If Loop above.

但是,“deserializedDictionary”始终为 null 或为空。基本上它从来没有出现在上面的 If 循环中。

I have been trying to figure this out for a while and am not able to. Please help

我一直试图弄清楚这一点,但无法解决。请帮忙

采纳答案by Anupdas

Your json object is an array try with NSArrayinstead of NSDictionary.

你的 json 对象是一个数组 try withNSArray而不是NSDictionary.

回答by Wain

Because the JSON returned is an array, not a dictionary. Try:

因为返回的 JSON 是一个数组,而不是一个字典。尝试:

NSLog(@"%@", NSStringFromClass([jsonObject class]));