将JSON对象转换为C#Object

时间:2011-07-26 18:47:16

标签: asp.net json jquery

如何将JSON对象映射到C#对象?

  var Data = JSON.stringify({
                    FirstName: "sdfsdf",
                    LastName: "sdfsdf", Age: "sdfsdf", Descrp: "sdfsdf"
                });

例如将Data转换为具有相同属性的C#类 我试过这个:

 var Data = JSON.stringify({
                FirstName: "sdfsdf",
                LastName: "sdfsdf", Age: "sdfsdf", Descrp: "sdfsdf"
            });
            $.ajax({
                type: "POST",
                url: "Services/CRUD.asmx/CreatePerson",
                data: Data,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    alert(msg.d);

                }
            });

但是当我用firebug检查时,这个错误又回来了:

{"Message":"Invalid web service call, missing value for parameter: \u0027PersonObj\u0027.","StackTrace":"   at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary`2 parameters)\r\n   at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 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"}

3 个答案:

答案 0 :(得分:4)

您绝对可以这样做,但您需要确保客户端对象与服务器端类结构,属性名称和参数名称完全匹配。

听起来您的服务器端方法需要PersonObj参数,但您不是在客户端以这种方式构造它。尝试这样的事情:

var Data = JSON.stringify({ 
  PersonObj: {
    FirstName: 'foo',
    LastName: 'bar',
    Age: 99,
    Descrp: 'foo person'
  }
});   

我已经在这里深入探讨了这一点:http://encosia.com/using-complex-types-to-make-calling-services-less-complex/

答案 1 :(得分:1)

您的PersonObj参数是什么类型的?假设它是这样的人:

public class Person
{
   public string FirstName { get;set;}
   public string LastName { get;set;}
   public string Age { get;set;}
   public string Descrp { get;set;}
}

您的WebService方法签名应该是:     public static returntype CreatePerson(string jsonPersonObject){}

您的Ajax数据参数应为:

$.ajax({
       type: "POST",
       url: "Services/CRUD.asmx/CreatePerson",
       data: {'jsonPersonObject' : Data },
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       success: function (msg) {
          alert(msg.d);
       }
});

然后在CreatePerson中,您必须将jsonPersonObject解析为Person。

执行此操作的常用方法是使用Json.NETJavaScriptSerializer from System.Web.Extensions.dll。可以找到更深入的信息herehere

答案 2 :(得分:1)

这样做:

 var context = new object();
 context.firstname = "sdfsdf";
 context.lname = "sdfsdf";
 context.age="sdfsdf";
 context.descrp= "sdfsdf"
 ajaxCall("functionname", context, ajaxCallSuccess, ajaxCallFailure, "pagename.aspx");

使用json2插件对你的上下文对象进行字符串化并以这种方式传递

function ajaxCall(funtionname, reqObject, successFn, errorFn, theaspxPage) {

    var dataObject = JSON.stringify(reqObject);

    //Call the page method  
    $.ajax({
        async: false,
        type: "POST",
        url: aspxPage + "/" + fn,
        contentType: "application/json;",
        data: "{'reqObject':" + dataObject + "}",
        dataType: "json",
        success: successFn,
        error: errorFn
    });
};

确保您的c#方法是静态的并接受一个对象 如果你想作为参数传递 修改 ajaxcall数据:dataobject,而不是reqobject:''