2012-04-13 67 views
0

在這個Objective-C編程中我很新。我的問題是,我需要創建一個名稱爲「X-FBR-App」的頭文件,並且此頭文件的內容是JSON字符串。 JSON字符串內容是5個參數。參數看起來像這樣:如何使用標題生成JSON對象?

NSString *nid = @":"; 
    NSString *vocab = @":"; 
    NSString *inturl = @"testoverview"; 
    NSString *mail = @"[email protected]"; 
    NSString *md5pw = @"password"; 

即時通訊使用iOS5和內置的JSON庫。任何想法如何做到這一點?

+0

你說的是HTTP頭? – CarlJ 2012-04-13 10:11:23

+0

是的,「X-FBR-App」是一個http標頭 – Lahib 2012-04-13 10:16:16

回答

1

這樣的事情...

NSString *nid = @":"; 
    NSString *vocab = @":"; 
    NSString *inturl = @"testoverview"; 
    NSString *mail = @"[email protected]"; 
    NSString *md5pw = @"password"; 

NSArray *jsonArray = [NSArray arrayWithObjects:inturl, mail, md5pw, nil]; // create your json array or dict 

NSError *error; 

// serialize data 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonArray 
                options:NSJSONWritingPrettyPrinted 
                error:&error]; 

if (! jsonData) { 
    NSLog(@"Got an error: %@", error); 
} else { 
    // get json string 
    NSString *jsonString = [[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] autorelease]; 

    // do a Request 

    NSString *url = @"your url"; 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:30.0]; 


    [request setValue:jsonString forHTTPHeaderField:@"Field You Want To Set"]; 

    [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
} 
+0

代碼的最後一行產生一個結果,是否會導致服務響應? – Lahib 2012-04-14 00:19:36

+0

否。它啓動異步URL加載。查看相關文檔。 – 2012-04-14 07:04:44