这是Raywenderlich编辑的JSON样本(http://www.raywenderlich.com/5492/working-with-json-in-ios-5).我需要进一步整合POST数据,例如用户名,以便从URL获取响应.我该怎么办?谢谢.
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1
#define kLatestKivaLoansURL [NSURL URLWithString: @"http://www.url.org/json.php"] //2
#import "ViewController.h"
@interface NSDictionary(JSONCategories)
+(NSDictionary*)dictionaryWithContentsOfJSONURLString:(NSString*)urlAddress;
-(NSData*)toJSON;
@end
@implementation NSDictionary(JSONCategories)
+(NSDictionary*)dictionaryWithContentsOfJSONURLString:(NSString*)urlAddress
{
NSData* data = [NSData dataWithContentsOfURL: [NSURL URLWithString: urlAddress] ];
__autoreleasing NSError* error = nil;
id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (error != nil) return nil;
return result;
}
-(NSData*)toJSON
{
NSError* error = nil;
id result = [NSJSONSerialization dataWithJSONObject:self options:kNilOptions error:&error];
if (error != nil) return nil;
return result;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: kLatestKivaLoansURL];
[self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSNumber* idd = [json objectForKey:@"id"];
NSString* name = [json objectForKey:@"name"];
NSString* email = [json objectForKey:@"email"];
// 3) Set the label appropriately
humanReadble.text = [NSString stringWithFormat:@"ID: %@ \nName: %@ \nEmail: %@", idd, name, email];
}
@end
Run Code Online (Sandbox Code Playgroud)
你必须做这样的事情来发布数据形式json.
-(void) retrieveData{
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"yoururl"]];
[request setHTTPMethod:@"GET"];
[request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
name.text=[[jsonArray objectAtIndex:0]objectForKey:@"title"];
til.text=[[jsonArray objectAtIndex:0]objectForKey:@"place"];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1899 次 |
| 最近记录: |