【问题标题】:How to convert JSON data to Class Object如何将 JSON 数据转换为类对象
【发布时间】:2011-03-30 13:14:31
【问题描述】:

JS 代码。

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

问题是:显示响应错误信息如下 -:

{"Message":"无效的网络服务调用, 参数缺失值: \u0027person\u0027.","StackTrace":" 在 System.Web.Script.Services.WebServiceMethodData.CallMethod(对象 目标,IDictionary2 parameters)\r\n at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary2 个参数)\r\n 在 System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext 上下文,WebServiceMethodData 方法数据,IDictionary`2 rawParams)\r\n 在 System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext 上下文,WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}

请提出解决方案。

【问题讨论】:

    标签: string json


    【解决方案1】:

    试试:

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

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

    1. person 而不是 person[]
    2. 人物对象周围没有引号

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-17
    • 2011-05-20
    • 2011-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多