2012-12-28 38 views
0

我正在嘗試使用JSON來解析PHP文件的某些輸出,希望能夠從我的MySQL數據庫返回一些數據。但是,我收到錯誤:-JSONValue失敗。錯誤是:令牌[A]的非法啓動。 php腳本返回一個用於在地圖上標註註釋的字典數組。我究竟做錯了什麼?使用JSON和PHP的iOS錯誤

- (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]; 
    } 
} 
+0

請張貼JSON,我認爲這是一個無效的JSON –

+0

我訪問的URL,這是什麼retured: 陣列([0] =>陣列([設備ID] => E19的iPad [緯度] => 45.511293 [經度] => -122.800233)[1] =>陣列([deviceid] => E05 iPad [latitude] => 45.54580829752314 [經度] => -122.9588931798935)[2] => Array([deviceid] => E01 iPad [latitude] => 45.520697139998525 [longitude] => -122.98941537737846)) 我認爲這不是有效的JSON。 – onevcat

回答

0

正如我所評論的,您的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字符串。

+1

我修復了我自己的問題。我沒有意識到我必須回聲json_encode($輸出)。這解決了它。 –