以下是我的服务器响应。我想解析并进一步使用它。
responseString:
{
"status": "1",
"MyData": [
{
"Value": 1,
"Name": "David",
"MusicURL": "http://www.mycomany.net/musicoutput/song1.wav",
"ImageURL": "http://www.mycomany.net/imageout/david.png"
},
{
"Value": 2,
"Name": "Martin",
"MusicURL": "http: //www.mycomany.net/musicoutput/song1.wav",
"ImageURL": "http: //www.mycomany.net/imageout/martin.png"
},
{
"Value": 3,
"Name": "Steve",
"MusicURL": "http: //www.mycomany.net/musicoutput/song1.wav",
"ImageURL": "http: //www.mycomany.net/imageout/david.png"
}
]
}
以下是我尝试进一步解析和使用它的代码。但是,问题是,它没有从NSJSONSerialization解析,而是我得到NULL。打印为responseDict :( null); jsonError:(null)。
请注意,当我这样做时 - > NSString * responseString = [[NSString alloc] initWithData:theResponseData encoding:NSUTF8StringEncoding]; ,我得到响应字符串作为上述输出。但是,我想将它作为NSDictionary供我进一步使用。
请帮助解决此问题。
NSMutableData * webData;
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
// [self callGetGroup];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSData *theResponseData = [[NSData alloc] initWithData:webData];
if (theResponseData)
{
//NSString *responseString = [[NSString alloc] initWithData:theResponseData encoding:NSUTF8StringEncoding];
//NSLog(@"responseString:%@ ;", responseString);
NSError *jsonError;
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:theResponseData options:0 error:&jsonError];
NSLog(@"responseDict:%@ ; jsonError: %@", responseDict, jsonError); // Printing as responseDict:(null) ; jsonError: (null)
[self handleResponse :responseDict];
}
}
-(void) handleResponse :(NSDictionary *) responsedata
{
NSString* value = NULL;
for (id key in responsedata)
{
NSDictionary *currentDict = (NSDictionary *) [responsedata objectForKey:key];
value = (NSString*)[currentDict objectForKey:@"status"];
if ( [value intValue]==1) // success
{
}
}
}
答案 0 :(得分:0)
您没有告诉我们错误是什么。
无论如何,JSON Feed中存在错误,因此很可能出现解析错误。如果JSON不正确,则生成的对象将为nil
。 JSONLint的输出:
Parse error on line 13:
... "MusicURL": http: //mycpmany.net
-----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['
答案 1 :(得分:0)
试试这个,“key”不是resposeDictionary中值的对象,ResposeDictionary从数据外观中保存更多的字典。所以你的“钥匙”不是价值的关键,它是一本字典。按照问题写的方式阅读输出有点困难,但是:
for (id object in responsedata)
{
NSDictionary *currentDict = (NSDictionary *)object;
value = (NSString*)[currentDict valueForKey:@"status"];
if ( [value length] > 0) // success
{
NSLog(@"Success! Status:%@",value);
}
}