Ali*_*Ali 1 iphone xcode objective-c ios
我是iOS新手.我创建了JSON NSDictionary这样的:
NSArray *keys = [NSArray arrayWithObjects:@"User", @"Password", nil];
NSArray *objects = [NSArray arrayWithObjects:@"Ali", @"2020", nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
Run Code Online (Sandbox Code Playgroud)
然后我可以NSString通过两种机制将其转换为:
1)
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:&error];
NSString *jsonString = nil;
if (! jsonData) {
NSLog(@"Got an error: %@", error);
} else {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
Run Code Online (Sandbox Code Playgroud)
2)
NSString *jsonString = [jsonDictionary JSONRepresentation];
Run Code Online (Sandbox Code Playgroud)
在第二种方式,我得到这个warning:
Instance method '-JSONRepresentation' not found (return type defaults to 'id')
Run Code Online (Sandbox Code Playgroud)
但是当我运行项目时,两种机制都可以正常工作:
NSLog(@"Val of json parse obj is %@",jsonString);
Run Code Online (Sandbox Code Playgroud)
你知道我怎么能以第二种方式删除警告?
我的主要目标是POST使用RESTful Web Service将json String转换为外部数据库.考虑到我的主要目标,基本上哪种方式更好?
NSJSONSerialization只要您的"目标受众"是iOS5 +,您就应该使用速度更快,直接使用iOS SDK
要将数据发布到Web服务,您需要沿着这些行创建请求...
NSDictionary * postDictionary = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"value1", @"value2", nil]
forKeys:[NSArray arrayWithObjects:@"key1", @"key2", nil]];
NSError * error = nil;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:postDictionary options:NSJSONReadingMutableContainers error:&error];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"your_webservice_post_url"]];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:jsonData];
NSURLConnection * myConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];
Run Code Online (Sandbox Code Playgroud)
请阅读NSURLConnectionDelegate 协议.
| 归档时间: |
|
| 查看次数: |
16701 次 |
| 最近记录: |