簡體   English   中英

從JSON響應解析坐標

[英]Parse coordinates from JSON response

我有帶數據的JSON

> {
>     "a": {
>         [{"X":12,"Y":6},{"X":24,"Y":9},{"X":91,"Y":23},{"X":36,"Y":79},{"X":69,"Y":71},{"X":55,"Y":19}],
>         "roam": true,
>         "device": true
>     } }

我用了

- (void)viewDidLoad {   
    [super viewDidLoad];

    responseData = [[NSMutableData data] retain];       
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://josn-example/json.json"]];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];            
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    label.text = [NSString stringWithFormat:@"Connection failed: %@", [error description]];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {      
    [connection release];

    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    NSLog(@"Response String : %@", responseString);

    [responseData release];

    NSError *error;
    SBJSON *json = [[SBJSON new] autorelease];
    NSArray *luckyNumbers = [json objectWithString:responseString error:&error];
    NSLog(@"luckNumber : %@",luckyNumbers);

    [responseString release];   

    if (luckyNumbers == nil)
        label.text = [NSString stringWithFormat:@"JSON parsing failed: %@", [error localizedDescription]];
    else {      
        NSMutableString *text = [NSMutableString stringWithString:@"Lucky numbers:\n"];

        for (int i = 0; i < [luckyNumbers count]; i++) 
            [text appendFormat:@"%@\n", [luckyNumbers objectAtIndex:i]];

        label.text =  text;
    }
}

我正在嘗試解析X和Y坐標,並在這些坐標上放置一個imageview。 請告知我該如何實現。

謝謝

首先,上面顯示的JSON代碼段不是有效的JSON。 這是有效的副本{{“ a”:[{“ X”:12,“ Y”:6},{“ X”:24,“ Y”:9},{“ X”:91,“ Y”: 23},{“ X”:36,“ Y”:79},{“ X”:69,“ Y”:71},{“ X”:55,“ Y”:19}],“漫游”: true,“ device”:true}。

假設您具有有效的JSON,則可以使用NSJSONSerialization將字符串轉換為可以輕松處理的FOundation對象(NSDictionary)。 示例代碼段(假設“ json”包含json字符串:

    NSData* jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
    NSError* error ;
    id jsonObj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
    NSLog (@"JSON Is %@ : Error is %@",jsonObj, error);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM