带有字符编码问题的JSON webservice参数

时间:2012-04-24 03:36:34

标签: objective-c json web-services character-encoding

我在我的iPhone应用程序中使用了一个Web服务(谁将JSON格式返回给我)。一切都很好,我可以使用参数调用我的Web服务(在下面的示例中参数是一个包含JSON格式的字符串)并从我的Web服务获取JSON答案。我的问题是我的Web服务接收带有转义字符(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
}

首先,收到的参数是否仍包含转义字符是正常的?如果是,我如何将字符串“user”:

{"Name":"aName","Date":"2012-04-24%2002:24:13%20+0000"}

进入那个:

{"Name":"aName","Date":"2012-04-24 02:24:13 +0000"}

否则,当我在iOS应用程序上构建请求时,我做错了吗?

1 个答案:

答案 0 :(得分:0)

这不是"character encoding"问题,本身。字符串"2012-04-24%2002:24:13%20+0000"只是URL-encoded

我真的不是Objective-C开发人员,但看起来这个问题源于你设置的Content-Type header

[request setValue:@"application/x-www-form-urlencoded; ... ]

我不确定你为什么要使用Content-Type: application/x-www-form-urlencoded,但这对我来说肯定闻起来很有趣。将JSON发送为application/json,这应该可以解决问题。

相关问题