如何将对象序列化为json并将其发送到Web服务?

时间:2011-06-30 13:24:12

标签: c# jquery ajax json serialization

如何将对象序列化为json并将其发送到Web服务?

var object = something....
function BindJson() {
        $.ajax({
            type: "POST",
            url: "NewPage.aspx/GetJson",
            data: "{}",
            contentType: "application/json",
            dataType: "json",
            success: function (data) {

            }
        })
    }

<body onload="BindJson();">

服务器:

[WebMethod]
        public static string GetSerializedJsonObject()
        {
            return "";
        }

4 个答案:

答案 0 :(得分:3)

这将适合您(下面的完整工作代码示例)。关键是传入Person对象。另外,我使用了一个简单的Web服务(myService.asmx)而不是aspx页面。如果不需要额外的开销,为什么还要费心呢?

关键是在客户端上创建一个Person对象,然后使用JSON.stringify将Person对象传递给Web服务。

<强>的Javascript

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js"></script>
<script type="text/javascript">
    function BindJson() {
        $.ajax({
            type: "POST",
            url: "myService.asmx/SerializeJson",
            data: JSON.stringify({ person:{ firstName: "Denny", lastName: "Cherian", department: "Microsoft PSS", address: { addressline1: "Microsoft India GTSC", addressline2: "PSS - DSI", city: "Bangalore", state: "Karnataka", country: "India", pin: "560028" }, technologies: ["IIS", "ASP.NET", "JavaScript", "AJAX"] }}),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data1) {
                alert(data1.d);
            },
            error: function (request, status, errorThrown) {
                alert(status);
            }
        });
    }

    $(document).ready(function() {
        BindJson();    
    });
</script>

<强> C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace TestProject
{
    /// <summary>
    /// Summary description for myService
    /// </summary>
    [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 myService : System.Web.Services.WebService
    {

        [WebMethod]
        public string SerializeJson(Person person)
        {
            return "Success";
        }

        public class Person
        {
            public string firstName { get; set; }
            public string lastName { get; set; }
            public string department { get; set; }
            public Address address { get; set; }
            public string[] technologies { get; set; }
        }

        public class Address
        {
            public string addressline1 { get; set; }
            public string addressline2 { get; set; }
            public string city { get; set; }
            public string state { get; set; }
            public string country { get; set; }
            public string pin { get; set; }            
        }
    }
}

答案 1 :(得分:1)

你可以用这个

  

var myJSONText =   JSON.stringify(myObject,replacer);

取自

http://www.json.org/js.html

希望它有所帮助。

答案 2 :(得分:0)

请查看此MSDN文章:JSON Serialization

Person p = new Person();
//Set up Person object...
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));
ser.WriteObject(stream1, p);

内存流将包含...

{“age”:42,”name”:”John”}

答案 3 :(得分:0)

这里有一个问题:Basic Simple Asp.net + jQuery + JSON example

您应该很容易地根据需要调整代码。唯一没有澄清的是如何在Javascript代码中将对象序列化为JSON,但是Billa Ustad已经回答了这个问题。

如果你想进一步讨论这个问题,可以在这里找到一篇优秀的教学文章:Full ASP.NET, LINQ, jQuery, JSON, Ajax Tutorial

记住:有时我们只想给鱼,但最终我们要学会如何捕捉自己的鱼。