在我的应用程序中,我需要解析从远程服务器接收到的 JSON 对象,而不是由我管理的。 我的应用程序从服务器获取的是一个 JSON 字符串,我将其转换为 NSDictionary。然后我试图检索一些 JSON 对象的值。 此时我面临以下问题: 我将以我正在检索的键“current_latitude:”的值为例。
如果我用检索到的字符串创建一个 NSLog,我会在我的控制台上得到这个:
VALUE=(
"-12.19061989"
)
显然,当我尝试将此字符串转换为 double 值时,应用程序崩溃了。
这是目前的代码:
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
for (NSString* key in json) {
id value = [json objectForKey:key];
NSLog(@"VALUE=%@",[value valueForKey:@"current_latitude"]);
NSLog(@"VALUE=%@",[value valueForKey:@"current_longitude"]);
}
我应该怎么做才能得到一个正常的字符串?
谢谢
已编辑
这是发出 JSON 请求的完整代码:
// request para descargar la posicion de los vehiculos disponibles
NSString *latitud = self.deviceLat;
NSString *longitud = self.deviceLon;
NSLog (@"latitud actual =%@",latitud);
NSLog (@"longitud actual =%@",longitud);
NSURL *apiURL = [NSURL URLWithString:
[NSString stringWithFormat:@"http://hidden here/?current_latitude=%@¤t_longitude=%@", latitud,longitud]];
NSURLRequest *request = [NSURLRequest requestWithURL:apiURL]; // this is using GET, for POST examples see the other answers here on this page
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if(data.length) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if(responseString && responseString.length) {
NSLog(@"dATOS RECIBIDOS=%@", responseString);
NSError *jsonError;
NSData *objectData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
for (NSString* key in json) {
id value = [json objectForKey:key];
// do stuff
NSLog(@"VALUE=%@",[value valueForKey:@"current_latitude"]);
NSLog(@"VALUE=%@",[value valueForKey:@"current_longitude"]);
//ponemos en el punto deseado un marcador de tipo PinDisponible
NSString *latstring = [value valueForKey:@"current_latitude"];
NSString *lonstring = [value valueForKey:@"current_longitude"];
NSLog(@"LATITUD=%@", latstring);
NSLog(@"LONGITUD=%@", lonstring);
//double latdouble = [latstring doubleValue];
//double londouble = [lonstring doubleValue];
//NSLog(@"latdouble: %f", latdouble);
//NSLog(@"londouble: %f", londouble);
//CLLocationCoordinate2D vehiculo = [mapView centerCoordinate];
//vehiculo.latitude = latdouble;
//vehiculo.longitude = londouble;
//PinDisponible *vehiculoDisponible = [[PinDisponible alloc] initWithTitle:@"Vehiculo disponible" location:vehiculo];
// [self.mapView addAnnotation:vehiculoDisponible];
}
}
}
}];
}
最佳答案
嗯,那是因为它不是一个字符串...它是一个带有字符串的数组(您在日志中看到的括号是数组 desciption
的一部分),所以我想你可以捕获
[[value valueForKey:@"current_latitude"]firstObject]
如果您确信这是从后端获得的信息。我希望这是有道理的
关于ios - 格式化 JSON 接收到的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28921292/