[英]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.