这是Raywenderlich(http://www.raywenderlich.com/5492/working-with-json-in-ios-5)的JSON编辑样本。我需要进一步整合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
答案 0 :(得分:5)
你必须做这样的事情来发布数据形式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"];
}
答案 1 :(得分:0)
您无法使用 dataWithContentsOfURL 发布数据。为此,您必须使用 NSMutableURLRequest 。请参阅下面的精彩教程:
http://www.mysamplecode.com/2013/04/ios-http-request-and-json-parsing.html