我正在我的 iPhone 应用程序中使用 Web 服务(返回 JSON 格式)。一切正常,我可以使用参数调用我的 Web 服务(在下面的示例中,参数是一个包含 JSON 格式的字符串)并从我的 Web 服务中获取 JSON 答案。我的问题是我的网络服务接收到带有转义字符(UTF8)的参数。这是代码:
// 1 - iOS app
NSString *parameters = @"&user={"Name":"aName","Date":"2012-04-24 02:24:13 +0000"}";
NSData *postData = [parameters dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *urlString = @"http://myWebService:80/AddUser";
NSURL *url = [NSURL URLWithString:urlString];
unsigned long long postLength = postData.length;
NSString *contentLength = [NSString stringWithFormat:@"%ull",postLength];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setValue:contentLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
// send the request...
------------------------------------------------------------------------------
// 2 - Web service
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void AddUser(string user)
{
Dictionary<string, string> userData = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(user);
string name = userData["Name"]; // OK here, name == "aName"
DateTime newDateTime = DateTime.Parse(userData["Date"]); // ERROR here because userData["Date"] returns "2012-04-24%2002:24:13%20+0000" so Parse method crash
// ... return the JSON answer
}
首先,接收到的参数仍然包含转义字符是否正常?如果是,我怎样才能把字符串“用户”:
{"Name":"aName","Date":"2012-04-24%2002:24:13%20+0000"}
进入那个:
{"Name":"aName","Date":"2012-04-24 02:24:13 +0000"}
否则,当我在我的 iOS 应用程序上构建我的请求时,我做错了什么吗?