我正在尝试将一个简单的json feed元素分配给标签。 我的json feed看起来像这样:
[{"code":501,"data":{"req":"0"}}]
我从网址检索后的代码:
NSURLResponse *response;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSString *theReply = [[NSString alloc] initWithBytes:[POSTReply bytes] length:[POSTReply length] encoding: NSASCIIStringEncoding];
NSLog(@"Reply: %@", theReply);
NSArray* json_object = [NSJSONSerialization
JSONObjectWithData:POSTReply
options:0
error:nil];
NSArray *json_object_line = [json_object objectAtIndex:0];
mainLabel.Text= [json_object_line valueForKey:@"code"];
我无法让这个工作。该应用程序只是崩溃,除非我删除最后2行。我尝试了很多其他选项(特别是最后两行)无济于事。
我有什么问题吗?
答案 0 :(得分:2)
您尝试将NSNumber
分配给标签的text
媒体资源。这是崩溃的原因。正确的方法是从JSON字段获取格式化字符串:
NSURLResponse *response;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:nil];
NSString *theReply = [[NSString alloc] initWithBytes:POSTReply.bytes
length:POSTReply.length
encoding:NSASCIIStringEncoding];
NSArray* json_object = [NSJSONSerialization JSONObjectWithData:POSTReply
options:0
error:nil];
NSDictionary *json_object_line = json_object[0];
mainLabel.text= [NSString stringWithFormat:@"%@", json_object_line[@"code"]];