从JSON响应中解析坐标

时间:2014-02-03 18:16:16

标签: ios iphone objective-c json ipad

我有数据的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。请告诉我如何实现这一目标。

由于

1 个答案:

答案 0 :(得分:0)

首先,上面显示的JSON代码段不是有效的JSON。这是一个有效的对应{     “一个”: [         {             “X”:12,             “Y”:6         },         {             “X”:24,             “Y”:9         },         {             “X”:91,             “Y”:23         },         {             “X”:36,             “Y”:79         },         {             “X”:69,             “Y”:71         },         {             “X”:55,             “Y”:19         }     ]     “漫游”:是的,     “设备”:是的 }。

假设您有一个有效的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);