我正在向 ASP.NET Web 服务发送 HTTP 请求,它以 JSON 形式返回响应(Web 服务最初返回一个 DataTable,它使用JSON.NET将其转换为 JSON)。
我收到的响应是 JSON。但随之而来的是一个 XML 标头!
2013-02-21 16:42:41.062 HttpRequestTest[6023:c07] <?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://www.my-comp.com/">[
{
"Int_Proj": 152,
"NewMailCnt": 79,
"DocsForRev": 2,
"DocsForRel": 1,
"Int_Sec": 2,
"UnregCnt": 3225,
"UnregAccss": 3,
"OutstMLCnt": 276,
"TBEdition": 1,
"ProjNo": "TESTPROJ1",
"ProjTitle": "TESTPROJ1 - DO NOT TOUCH TESTPROJ1 - DO NOT TOUCH TESTPROJ1",
"ServerName": "ISURU",
"ServerUrl": "ISURU/myserver/",
"Int_Server": 1,
"Int_Key": 2,
"IsGblAdrBk": 0
},
{
"Int_Proj": 160,
"NewMailCnt": 11,
...
这是调用 Web 服务的 Objective-C 代码。
NSURL *url = [NSURL URLWithString:@"http://isuru/TBWebService/Session.asmx/GetUserProjectList?userID=dr&companyID=qas&password=david&errorMsg=''"];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
NSData *urlData;
NSURLResponse *response;
NSError *error;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
NSString *returnedData = [[NSString alloc] initWithData:urlData
encoding:NSUTF8StringEncoding];
NSLog(@"%@", returnedData);
这是 ASP.NET Web 服务方法的 C# 代码。
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Logon(string userID, string companyID, string password, string projNo)
{
MySoftware.TestSoft.User user = new MySoftware.TestSoft.User();
DataTable userTable = user.ListUserAccessProjects(userID, companyID, password, "", "");
if (userTable.Rows.Count == 0)
{
string jsonRet = JsonConvert.SerializeObject("ERROR - Invalid User ID, Company ID or Password.", Formatting.Indented);
return jsonRet;
}
DataRow[] projectEntries = userTable.Select(String.Format("ProjNo='{0}'", projNo));
if(projectEntries.Length==0)
{
string jsonRet = JsonConvert.SerializeObject("ERROR - Invalid Project Number.", Formatting.Indented);
return jsonRet;
}
int int_Project = Convert.ToInt32(projectEntries[0]["int_proj"]);
MySoftware.TestSoft.Logon logon = new MySoftware.TestSoft.Logon();
try
{
bool isSameServer = false;
string sessonKey = logon.Login(Convert.ToInt32(projectEntries[0]["int_Key"]), Convert.ToInt32(projectEntries[0]["Int_Server"]), userID, companyID, password, int_Project, out isSameServer);
string json = JsonConvert.SerializeObject(sessonKey, Formatting.Indented);
return json;
}
catch (ApplicationException ex)
{
string jsonRet = JsonConvert.SerializeObject("ERROR - " + ex.Message, Formatting.Indented);
return jsonRet;
}
}
在 SO 上已经提出了同样的问题,我尝试了那里提到的所有内容,但无济于事。此外,它们都与 Objective-C 无关。
如何在没有 XML 标头的情况下获得 JSON 响应?