iOS中

2013-10-20 44 views
1

創建JSON字符串如何在iOS的iOS中

創建JSON字符串HTTP請求,我有這些值:

{"name":"customer6","pass":"customer6", "mail":"[email protected]","user_roles":"5", "field_login_pin_value":{"und":[{"value":"2324"}]} } 

那麼如何使JSON字符串超出這個數據的?

這裏是我的代碼:

NSArray *keys = [NSArray arrayWithObjects:@"name",@"pass",@"mail",@"user_roles",@"field_login_pin_value", nil]; 

NSArray *objects = [NSArray arrayWithObjects:@"customer6",@"customer6",@"[email protected]",@"5",@"{\"und\":[{\"value\":\"2324\"}]", nil]; 

NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys]; 

NSString *jsonString = [jsonDictionary JSONRepresentation]; 


NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://xxxxxxxx/register.json"]]; 
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
[request setValue:jsonString forHTTPHeaderField:@"json"]; 
[request setHTTPMethod:@"POST"]; 
[request setHTTPBody:jsonData]; 

nsconnection= [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

當我打的Web服務請求時,我得到如下回應:

"form_errors" =  { 
     "field_login_pin_value][und][0][value" = "PIN value field is required."; 
    }; 
} 

我總是得到同樣的錯誤

任何人都可以讓我知道我的實現有什麼問題?

+0

你只是部分構建了JSON。字符串',@「{\」und \「:[{\」value \「:\」2324 \「}]」'幾乎肯定應該被編碼爲JSON,而不是字符串。請參閱json.org以瞭解JSON語法 - 您要創建的是帶有一個鍵入sith「und」的條目的字典。那一個條目是一個包含一個元素的數組,並且一個數組元素是一個帶有「value」鍵和值「2324」的字典。 –

回答

2

我想JSONRepresentation正在格式化"{\"und\":[{\"value\":\"2324\"}]"作爲它的字面字符串,而不是字典內的字典內的字典中的值。你應該製作整個字典數組字典結構。

NSDictionary *jsonDictionary = @{ 
    @"name" : @"customer6", 
    @"pass" : @"customer6", 
    @"mail" : @"[email protected]", 

    @"user_roles" : @"5", 

    @"field_login_pin_value" : @{ 
     @"und":@[ 
      @{ 
       @"value" : @"2324" 
      } 
     ] 
    } 
}; 

你可以,當然,聚結pin_value值單行線​​,這僅僅是爲了清晰:這將如果您使用數組和字典文字都更加容易。

+0

Thanx爲這個答案:) –