我有这个json字符串
{
"@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"
}
]
}
我想解析它,我写了这段代码
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个元素,请帮助
答案 0 :(得分:1)
你正在做一个initWithContentsOfFile但传入一个字符串。你试过简单的[responseString JSONValue]吗?您的代码表明responseString具有您尝试打开的文件的PATH,而不是您自己的完整响应字符串。
答案 1 :(得分:1)
initWithContentsOfFile
采用包含文件路径的字符串(例如“/users/mehdi/documents/myFile.txt”)。您似乎传递了实际的JSON字符串,这不是文件路径。因此,initWithContentsOfFile
可能会返回nil
。
通过询问:
来检查if (myJSON == nil) NSLog(@"myJSON variable == nil!");
如果为零,那么您的代码也会将json
和citysList
设置为nil。
试试这个:
NSDictionary *json = [responseString JSONValue];
NSArray *citysList = [json objectForKey:@"city"];
NSLog(@" number of element : %d", [citysList count]);