C# 通过JSON.Net和C将JSON作为字符串传递回解析
我的javascript/jquery前端如下:C# 通过JSON.Net和C将JSON作为字符串传递回解析,c#,javascript,jquery,ajax,json.net,C#,Javascript,Jquery,Ajax,Json.net,我的javascript/jquery前端如下: var jsonData = JSON.stringify({ 'myType': 'typeOfFile', tmyData: { 'SelectedYears': myArray["SelectedYears"], 'columns': myArray["Columns"],
var jsonData = JSON.stringify({
'myType': 'typeOfFile',
tmyData:
{
'SelectedYears': myArray["SelectedYears"],
'columns': myArray["Columns"],
'rows': myArray["Rows"],
'filters': myArray["Filters"]
}
});
alert(jsonData);
$.ajax({
type: "POST",
url: "mywebservice.asmx/Create",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, status, error) {
//alert the error if needed
//$("#result").html("Sorry there is an error: " xhr.responseText);
alert('Error: ' + xhr.responseText);
},
success: function (responseData) {
alert(responseData);
// show the response data from webservice. Note: the d represent the object property data passed by webservice. It can an object of properties or just single property
//$("#result").html("The id is " + responseData.d.ID + " And Name is " + responseData.d.Name + " And Email is " + responseData.d.Email);
}
});
My webservice.asmx文件:
[WebService(Namespace = "http://tempuri.org")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 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 mywebservice : System.Web.Services.WebService
{
[WebMethod]
public string Create(string myType, string myData)
{
//JToken token = JObject.Parse(myData.ToString());
//JObject obj = (JObject)token.SelectToken("SelectedYears");
return "Hello World";
}
}
上面的这个崩溃是因为我想要的第二个参数是字符串,但它不被接受。如果我将其更改为object,则它会工作。如何将其转换为字符串,以便使用JSON.Net对其进行解析?我必须说我没有尝试过,但我的猜测是,您必须将myData的类型更改为匹配对象,因为您的js对象不是字符串 例如:
class MyData
{
// Whatever are your properties ex: SelectedYears, columns etc..
}
将签名更改为
public string Create(string myType, MyData myData)
您希望返回JSON,但返回字符串Hello World?这只是一个测试,我想在返回之前解析正在解析的字符串/对象init失败。您是否尝试将参数名从tmyData修复到myData,因为您在那里有一个额外的“m”字符。