我成功地从我的服务器获取数据。得到它后,我将数据发送到函数进行解析;
- (void)readIn:(NSMutableData *)s {
NSLog(@"Reading in the following:");
NSString * prints = [[NSString alloc] initWithData:s encoding:NSUTF8StringEncoding];
NSLog(@"%@", prints);
NSError *error = nil;
NSData *jsonData = [[NSData alloc] initWithData:s];
if (jsonData) {
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
if ([jsonObjects isKindOfClass: [NSArray class]])
NSLog(@"yes we got an Array");
else if ([jsonObjects isKindOfClass: [NSDictionary class]])
NSLog(@"yes we got an dictionary");
else
NSLog(@"neither array nor dictionary!");
if (error) {
NSLog(@"error is %@", [error localizedDescription]);
return;
}
NSArray *keys = [jsonObjects allKeys];
for (NSString *key in keys) {
NSLog(@"%@ is %@",key, [jsonObjects objectForKey:key]);
}
} else {
// Handle Error
}
}
现在我在控制台上的打印是:
2012-08-17 13:59:57.667 TaraftarlikOyunu[1157:c07] Reading in the following:
2012-08-17 13:59:57.667 TaraftarlikOyunu[1157:c07] {"uID":"5878341","tm":"fb","hh":122,"pt":75,"coin":500,"ll":1,"qlevel":1,"coect":true,"potWeekly":{"pts":75,"intval":604800000},"acent":{"chamunt":0},"mes":[]}
2012-08-17 13:59:57.668 TaraftarlikOyunu[1157:c07] neither array nor dictionary!
2012-08-17 13:59:57.670 TaraftarlikOyunu[1157:c07] error is The operation couldn’t be completed. (Cocoa error 3840.)
对我来说,这似乎是合法的 json 对象。我在哪里做错了?
我正在使用 nsstream 从服务器获取数据;这是我获取数据的代码:
case NSStreamEventHasBytesAvailable: {
if(stream == inputStream) {
NSLog(@"inputStream is ready.");
uint8_t buf[1024];
unsigned int len = 0;
len = [inputStream read:buf maxLength:1024];
NSLog(@"length %i", len);
if(len > 0) {
NSMutableData* data=[[NSMutableData alloc] initWithLength:0];
[data appendBytes: (const void *)buf length:len];
[self readIn:data];
}
}
break;
}