我正在开发需要与 Windows 服务器共享数据的 iDevice 应用程序。我查看了网络上的一些示例,并提出了下面列出的实现。iOS 应用程序将 JSON 发送到 Web 服务器并接收返回的 JSON 响应。然而,反应不是我所期望的。我收到{"d": "{\"name\": \"John Doe\", \"email\": \"test@gmail.com\"}"}
,而不是{\"name\": \"John Doe\", \"email\": \"test@gmail.com\"}
任何想法“d”来自哪里?
iOS 代码:
-(void)checkWithServer {
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSURL *postURL = [NSURL URLWithString: @"http://texas/WebSite3/Service.asmx/doSomething"];
NSDictionary *jsonDict = [[NSDictionary alloc] initWithObjectsAndKeys:
@"test@gmail.com", @"email",
@"John Doe", @"name",
nil];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: postURL
cachePolicy: NSURLRequestUseProtocolCachePolicy
timeoutInterval: 60.0];
[request setHTTPMethod: @"POST"];
[request setValue: @"application/json" forHTTPHeaderField: @"Accept"];
[request setValue: @"application/json; charset=utf-8" forHTTPHeaderField: @"content-type"];
[request setHTTPBody: jsonData];
[NSURLConnection sendAsynchronousRequest: request
queue: queue
completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error) {
if (error || !data) {
// Handle the error
} else {
// Handle the success
}
}
];
}
网络服务器代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Xml;
using System.Xml.Linq;
using System.Data;
using System.Data.SqlClient;
[WebService(Namespace = "http://texas/WebSite3")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
public Service () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string doSomething(string email, string name)
{
return "{\"name\": \"" + name + "\", \"email\": \"" + email + "\"}";
}
}
显然,网络服务器足够聪明,可以将 JSON 分开并分配变量名称和电子邮件。