将 JSON 解码为 NSArray 或 NSDictionary
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10121693/
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
Decode JSON to NSArray or NSDictionary
提问by arachide
I hope to decode the JSON data below:
我希望解码下面的JSON数据:
{
"content":
[
{
"1":"a",
"2":"b",
"3":"c",
"4":"d",
"mark":"yes"
}
]
}
Not sure if put it in NSArray or NSDictionary
不确定是放在 NSArray 还是 NSDictionary 中
Welcome any comment
欢迎任何评论
回答by Andrea
which iOS version are you using? in iOS 5 you have the NSJSONSerializationclass to parse JSON data, if you need to target older iOSs or MAC OSX you should use third parties lib such as SBJSON. The string posted will be a NSDictionary with an array with one dictionary. The array will be accessible using the key @"content"
您使用的是哪个 iOS 版本?在 iOS 5 中,您有NSJSONSerialization解析 JSON 数据的类,如果您需要针对较旧的 iOS 或 MAC OSX,您应该使用第三方库,例如SBJSON. 发布的字符串将是一个带有一个字典的数组的 NSDictionary。可以使用密钥访问该数组@"content"
In code:
在代码中:
NSString * jsonString = @"blblblblblb";
NSStringEncoding encoding;
NSData * jsonData = [jsonString dataUsingEncoding:encoding];
NSError * error=nil;
NSDictionary * parsedData = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
In SWIFT 2.0:
在 SWIFT 2.0 中:
let jsonString = "blblblblblb"
let encoding = NSUTF8StringEncoding
let jsonData = jsonString.dataUsingEncoding(encoding)
guard let jData = jsonData else {return}
do {
let parsedData = try NSJSONSerialization.JSONObjectWithData(jData, options: [])
} catch let error {
print("json error: \(error)")
}
[UPDATE]
The NSJSONSerializationclass is also available for 10.7 my comment wasn't correct.
[更新] 该NSJSONSerialization课程也适用于 10.7 我的评论不正确。
回答by JeremyP
That particular string will decode into an NSDictionary because the outermost thing is a JSON object which maps onto a NSDictionary for every JSON implementation I have ever seen. If you want to process an arbitrary string, you'll need to test what you get back
该特定字符串将解码为 NSDictionary,因为最外层是一个 JSON 对象,它映射到我见过的每个 JSON 实现的 NSDictionary。如果要处理任意字符串,则需要测试返回的内容
NSError *jsonError;
id parsedThing = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
if (parsedThing == nil)
{
// error
}
else if ([parsedThing isKindOfClass: [NSArray class]])
{
// handle array, parsedThing can be cast as an NSArray safely
}
else
{
// handle dictionary, parsedThing can be cast as an NSDictionary
// NB only dictionaries and arrays allowed as long as NSJSONReadingAllowFragments
// not specified in the options
}
回答by Vaibhav Saran
stringWithContentsOfFile:encoding:is deprecated in iOS<6
stringWithContentsOfFile:encoding:已弃用 iOS<6
for iOS 6+
为了 iOS 6+
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"contents" ofType:@"json"];
NSError * error=nil;
NSString *jsonString = [NSString stringWithContentsOfFile:filePath encoding:nil error:&error];
NSData * jsonData = [jsonString dataUsingEncoding:nil];
NSArray * parsedData = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
contents.jsonfile is in your bundle.
contents.json文件在您的捆绑包中。
回答by Nikhil Mathew
I used google speech recognition API and I was getting a json response which was not directly parsable on iOS. Results samples were like :
我使用了谷歌语音识别 API,我得到了一个无法在 iOS 上直接解析的 json 响应。结果样本如下:
First I tried saying Hello 1 2 3 which was recognised without issues. Json response was :
首先,我尝试说 Hello 1 2 3 被识别没有问题。Json 回应是:
{"result":[]}
{"result":[{"alternative":[{"transcript":"hello 123","confidence":0.59780568},{"transcript":"hello 1 2 3"}],"final":true}],"result_index":0}
Or when talked for too long, I got a 404 HTML like below :
或者当谈话太久时,我得到了一个 404 HTML,如下所示:
<html><title>Error 400 (Bad Request)!!1</title></html>
And when I spoke gibberish , I got :
当我胡言乱语时,我得到了:
{"result":[]}
So to parse all such response, I used the below code :
因此,为了解析所有此类响应,我使用了以下代码:
NSString *msg = @"Could not synthesize !";
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"responseString: %@",responseString);
if([responseString containsString:@"transcript"]&&responseString.length>25)
{
responseString = [responseString stringByReplacingOccurrencesOfString:@"{\"result\":[]}" withString:@""];
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[responseString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
if(dictionary!=nil)
if(dictionary.allValues.count>0)
{
NSArray *array =[dictionary valueForKeyPath:@"result.alternative.transcript"];
if(array)
{
NSArray *array2 = [array objectAtIndex:0];
if(array2)
{
NSLog(@"%@",[array2 objectAtIndex:0] );
msg = [array2 objectAtIndex:0];
};
}
}
}
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Google Response" message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
Hope this helps someone.
希望这可以帮助某人。
回答by hypercrypt
You can do the following:
您可以执行以下操作:
NSData *data = ...; //JSON data
NSError *jsonError = nil;
[NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
You will get back an NSDictionarycontaining an NSArraycontaining a single NSDictionarycontaining five NSStringobjects.
您将返回一个NSDictionary包含一个NSArray包含一个NSDictionary包含五个NSString对象的单个。

