如何将JSON数据转换为类对象

时间:2011-03-30 13:14:32

标签: string json

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#代码。

[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; }
    }
}

问题在于:显示以下响应错误消息 - :

  

{“消息”:“无效的网络服务电话,   缺少参数值:   \ u0027person \ u0027。“,”StackTrace“:”at   System.Web.Script.Services.WebServiceMethodData.CallMethod(对象   target,IDictionary 2 parameters)\r\n at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary 2个参数)\ r \ n   在   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”}

请建议解决方案。

1 个答案:

答案 0 :(得分:1)

尝试:

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

它与您的代码在两个地方不同:

  1. person代替person[]
  2. 没有人物对象的引用