开发者

How to convert JSON data to Class Object

JS Code.

// this is person class constructor.
function personClass(id, name, address, phone) {
    this.Id = id;
    this.Name = name;
    this.Address = address;
    this.Phone = phone;
}
var person = new Array();
person.push(new personClass("101", $('#txtName').val(), $('#txtAddress').val(), $('#txtPhone').val());

AjaxRequest = function ("PersonInfo.asmx/AddNewPerson", "{'person[]':'" + JSON.stringify(person) + "'}", successcallback, errorcallback) {
    $.ajax({
        type: "POST",
        url: url,
        data: param,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: successcallback,
        error: errorcallback
    });
}

C# Code.

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod(EnableSession = true)]
public string AddProduct(Person[] person)
{
    return person[0].Id;
}

public class Person
{
    private string _id = String.Empty;
    private string Id
    {
        get { return _id; }
        set { _id = value; }
    }
    private string _name = String.Empty;
    private string Name
    {
        get { return _name; }
        set { _name = value; }
    }
    private string _address = String.Empty;
    private string Address
    {
        get { return _address; }
        set { _address = value; }
    }
    private string _phone = String.Empty;
    private string Id
    {
        get { return _phone; }
        set { _phone = value; }
    }
}

Problem is that : show response error message following -:

{"Message":"Invalid web service call, missing value for parameter: \u0027person\u0027.","StackTrace":" at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary2 parameters)\r\n at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary2 parameters)\r\n at System.Web.Script.Services开发者_如何学运维.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}

Please suggest the solution.


Try:

"{'person':" + JSON.stringify(person) + "}"

It differs from your code in two places:

  1. person instead of person[]
  2. No quotes around person object
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜