如何在 iOS 中为 HTTP 请求创建 JSON 字符串
我有这些值(value)观:
{"name":"customer6","pass":"customer6", "mail":"customer6@xy.com","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",@"customer6@xy.com",@"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];
当我点击网络服务请求时,我得到以下响应:
"form_errors" = {
"field_login_pin_value][und][0][value" = "PIN value field is required.";
};
}
我总是得到同样的错误
任何人都可以让我知道我的实现有什么问题吗?
最佳答案
我想 JSONRepresentation
正在将 "{\"und\":[{\"value\":\"2324\"}]"
格式化为它是文字字符串,而不是字典中数组中字典中的值。你应该制作整个 dict-array-dict 结构。如果您使用数组和字典文字,这一切都会更容易:
NSDictionary *jsonDictionary = @{
@"name" : @"customer6",
@"pass" : @"customer6",
@"mail" : @"customer6@xy.com",
@"user_roles" : @"5",
@"field_login_pin_value" : @{
@"und":@[
@{
@"value" : @"2324"
}
]
}
};
当然,您可以将 pin_value 值合并到一行,这只是为了清楚起见。
关于ios - 在 iOS 中创建 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19481538/