【问题标题】:iOS error using JSON and php使用 JSON 和 php 的 iOS 错误
【发布时间】:2012-12-28 04:02:07
【问题描述】:

我正在尝试使用 JSON 来解析 php 文件中的一些输出,该文件有望从我的 MySQL 数据库中返回一些数据。但是,我收到错误消息:-JSONValue 失败。错误是:令牌 [A] 的非法开始。 php 脚本返回一个字典数组,用于在地图上绘制注释。我做错了什么?

- (void)getDeviceLocations {

    NSLog(@"Getting Device Locations");

    NSString *hostStr = @"http://98.246.50.81/firecom/api/getdevicelocations.php";
    NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:hostStr]];
    NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
    id object = [serverOutput JSONValue];
    NSMutableArray *array = (NSMutableArray *)object;

    for (NSDictionary *dictionary in array) {

        CLLocationCoordinate2D coord = {[[dictionary objectForKey:@"latitude"] doubleValue], [[dictionary objectForKey:@"longitude"] doubleValue]};

        Annotation *ann = [[Annotation alloc] init];
        ann.title = [dictionary objectForKey:@"deviceid"];
        ann.coordinate = coord;
        [mapView addAnnotation:ann];
    }
}

【问题讨论】:

  • 请发布json,我认为这是一个无效的json
  • 我访问了 url,这是返回的内容: Array ( [0] => Array ( [deviceid] => E19 iPad [latitude] => 45.511293 [longitude] => -122.800233 ) [ 1] => Array ([deviceid] => E05 iPad [latitude] => 45.54580829752314 [longitude] => -122.9588931798935) [2] => Array ([deviceid] => E01 iPad [latitude] => 45.520697139998525 [longitude] => -122.98941537737846 ) ) 我认为它不是有效的 JSON。

标签: ios json nsarray nsdictionary


【解决方案1】:

正如我所评论的,您的 JSON 无效。您应该像这样返回一个有效的 JSON(使用您的数据)

[
  {
    "latitude": 45.5113,
    "deviceid": "E19 iPad",
    "longitude": "-122.800233"
  },
  {
    "latitude": 45.5458,
    "deviceid": "E05 iPad",
    "longitude": "-122.9588931798935"
  },
  {
    "latitude": 45.5207,
    "deviceid": "E01 iPad",
    "longitude": "-122.98941537737846"
  }
]

我觉得还是尝试使用default php JSON encode method json_encode生成json字符串比较好。

【讨论】:

  • 我自己解决了问题。我没有意识到我必须回显 json_encode($output)。这解决了它。
猜你喜欢
  • 1970-01-01
  • 2010-10-10
  • 2012-12-19
  • 2022-01-26
  • 1970-01-01
  • 1970-01-01
  • 2018-12-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多