如何在Objective-C中解析JSON [英] How to parse JSON in Objective-C
问题描述
我有这个json字符串
i have this json string
{
"@uri": "http://localhost:8080/TunisairRESTful/resources/cities/",
"city": [
{
"@uri": "http://localhost:8080/TunisairRESTful/resources/cities/ABJ/",
"agencyCollection": {
"@uri": "http://localhost:8080/TunisairRESTful/resources/cities/ABJ/agencyCollection/"
},
"codecit": "ABJ",
"country": {
"@uri": "http://localhost:8080/TunisairRESTful/resources/cities/ABJ/country/"
},
"namecit": "ABIDJAN"
},
{
"@uri": "http://localhost:8080/TunisairRESTful/resources/cities/ALG/",
"agencyCollection": {
"@uri": "http://localhost:8080/TunisairRESTful/resources/cities/ALG/agencyCollection/",
"agency": [
{
"@uri": "http://localhost:8080/TunisairRESTful/resources/cities/ALG/agencyCollection/3/"
},
{
"@uri": "http://localhost:8080/TunisairRESTful/resources/cities/ALG/agencyCollection/4/"
}
]
},
"codecit": "ALG",
"country": {
"@uri": "http://localhost:8080/TunisairRESTful/resources/cities/ALG/country/"
},
"namecit": "ALGER"
},
{
"@uri": "http://localhost:8080/TunisairRESTful/resources/cities/AMS/",
"agencyCollection": {
"@uri": "http://localhost:8080/TunisairRESTful/resources/cities/AMS/agencyCollection/",
"agency": [
{
"@uri": "http://localhost:8080/TunisairRESTful/resources/cities/AMS/agencyCollection/5/"
},
{
"@uri": "http://localhost:8080/TunisairRESTful/resources/cities/AMS/agencyCollection/6/"
}
]
},
"codecit": "AMS",
"country": {
"@uri": "http://localhost:8080/TunisairRESTful/resources/cities/AMS/country/"
},
"namecit": "AMSTERDAM"
}
]
}
我想解析它,我写了这段代码
I want to parse it, I wrote this code
NSString *myJSON = [[NSString alloc] initWithContentsOfFile:responseString encoding:NSUTF8StringEncoding error:NULL];
NSDictionary *json = [myJSON JSONValue];
//NSLog(responseString);
NSArray *citysList = [json objectForKey:@"city"];
NSLog(@"ok");
NSLog(@" number of element : %@", [citysList count]);
但是我有0个元素,请帮助
But I have 0 number of element , help please
推荐答案
迈克尔是正确的.这是更详细的答案:
Michael is right. Here's a more detailed answer:
initWithContentsOfFile
采用包含文件路径的字符串(例如"/users/mehdi/documents/myFile.txt").您似乎正在传递您的实际JSON字符串,这不是文件路径.结果,initWithContentsOfFile
可能返回nil
.
initWithContentsOfFile
takes a string containing a file path (e.g. "/users/mehdi/documents/myFile.txt"). You seem to be passing in your actual JSON string, which isn't a file path. As a result, initWithContentsOfFile
is probably returning nil
.
通过询问以下内容进行确认:
Check this by asking:
if (myJSON == nil) NSLog(@"myJSON variable == nil!");
如果为nil,则您的代码还将json
和citysList
设置为nil.
If it is nil, then your code is also setting json
and citysList
to nil.
尝试一下:
NSDictionary *json = [responseString JSONValue];
NSArray *citysList = [json objectForKey:@"city"];
NSLog(@" number of element : %d", [citysList count]);
这篇关于如何在Objective-C中解析JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!