我在visual studio 2010中创建了一个Rest webservice,如下所示:
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class DocService
{
[WebInvoke(ResponseFormat = WebMessageFormat.Json,UriTemplate = "", BodyStyle = WebMessageBodyStyle.Wrapped)]
public data GetCollection(Stream streamdata)
{
}
}
用户将使用json数据向此服务发送请求:
var JSONObject = '{"pCode": "123456789","mCode": "001","tCode": "","dArr": [{ "dCode": 26 },{ "dCode": 27 }],"sId": "sk"}';
var jsonData = JSON.parse(JSONObject);
var request = $.ajax({
url: "http://myIp/path/to/service",
type: "POST",
data: jsonData,
dataType: "json",
success: function (data) {
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
第一个问题:如何在我的代码中访问该json? 现在我喜欢这样(但是json数组不能序列化正确):
StreamReader reader = new StreamReader(streamdata);
string res = reader.ReadToEnd();
reader.Close();
reader.Dispose();
string resDecode = HttpUtility.UrlDecode(res);
NameValueCollection nvc = HttpUtility.ParseQueryString(resDecode);
var json = new JavaScriptSerializer().Serialize(
nvc.AllKeys.ToDictionary(k => k, k => nvc[k])
);
输出:
res = "pCode=123456789&mCode=001&tCode=&dArr%5B0%5D%5BdCode%5D=26&dArr%5B1%5D%5BdCode%5D=27&sId=sk"
resDecode= "pCode=123456789&mCode=001&tCode=&dArr[0][dCode]=26&dArr[1][dCode]=27&sId=sk"
nvc = {pCode=123456789&mCode=001&tCode=&dArr%5b0%5d%5bdCode%5d=26&dArr%5b1%5d%5bdCode%5d=27&sId=sk}
json = "{\"pCode\":\"123456789\",\"mCode\":\"001\",\"tCode\":\"\",\"dArr[0][dCode]\":\"26\",\"dArr[1][dCode]\":\"27\",\"sId\":\"sk\"}"
第二个问题:在ajax中,在发送请求后,它始终显示错误,xhr.status
和thrownError
为0且为null但 Fiddler 我可以看到json输出
答案 0 :(得分:1)
回答第一个问题:
在c#中使用json的最佳方法是创建一个具有精确名称和json对象类型的属性的类,然后像这样反序列化json:
RequestClass reqParam = new RequestClass(); //Class with properties same as json object
StreamReader reader = new StreamReader(streamdata);
string res = reader.ReadToEnd();
reader.Close();
reader.Dispose();
JavaScriptSerializer js = new JavaScriptSerializer();
reqParam = js.Deserialize<RequestClass>(res);
回答第二个问题:
我的最终javascript是这样的,工作正常:
var JSONObject = '{"pCode": "123456789","mCode": "001","tCode": "","dArr": [{ "dCode": 26 },{ "dCode": 27 }],"sId": "sk"}';
//Delete parse line
var request = $.ajax({
url: "http://myIp/path/to/service",
type: "POST",
contentType: "application/json", //Added
data: JSONObject, // This line changed
dataType: "json",
success: function (data) {
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});