ios 如何将 JSON 序列化数据转换为 NSDictionary
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12603047/
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
How to convert JSON serialized data to NSDictionary
提问by Rajesh
I have used this method,
我用过这个方法,
NSDictionary *jsonObject=[NSJSONSerialization
JSONObjectWithData:jsonData
options:NSJSONReadingMutableLeaves
error:nil];
NSLog(@"jsonObject is %@",jsonObject);
It's printing "jsonObject is null".
Is there any problem with "error:nil".
I am not using any url or connection methods.
I have a json file and I want to display it in a table.
它正在打印“jsonObject 为空”。
“error:nil”有什么问题吗?
我没有使用任何 url 或连接方法。
我有一个 json 文件,我想在表格中显示它。
回答by amit soni
Please Try the following Code.
请尝试以下代码。
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSArray* latestLoans = [json objectForKey:@"loans"];
NSLog(@"loans: %@", latestLoans);
回答by iAhmed
Just in case anyone is here to see swift code:
以防万一有人在这里查看快速代码:
NSData to NSDictionary
NSData 到 NSDictionary
let dictionary:NSDictionary = NSKeyedUnarchiver.unarchiveObjectWithData(jsonData)! as NSDictionary
NSData to NSString
NSData 到 NSString
let resstr = NSString(data: res, encoding: NSUTF8StringEncoding)
回答by iAhmed
Check your json input, could it be that your root element is neither a dictionary nor an array? The documentation says you have to specify NSJSONReadingAllowFragments as the option in this case.
检查您的 json 输入,是否您的根元素既不是字典也不是数组?文档说在这种情况下你必须指定 NSJSONReadingAllowFragments 作为选项。
#import <Foundation/Foundation.h>
int main(int argc, char *argv[]) {
NSAutoreleasePool *p = [[NSAutoreleasePool alloc] init];
NSData *jsonData = [@"{ \"key1\": \"value1\" }" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonObject=[NSJSONSerialization
JSONObjectWithData:jsonData
options:NSJSONReadingMutableLeaves
error:nil];
NSLog(@"jsonObject is %@",jsonObject);
[p release];
}
Output:
输出:
2012-09-26 16:06:51.610 Untitled[19164:707] jsonObject is {
key1 = value1;
}
回答by Luis B
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
This is just a more succinct version of the top post.
这只是顶帖的更简洁版本。
回答by Softlabsindia
let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
让convertedJsonIntoDict = 尝试JSONSerialization.jsonObject(with: data!, options: []) as? NSD字典