gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:11:18 25 4
gpt4 key购买 nike

如何将对象序列化为 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 "";
}

最佳答案

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

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

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

关于c# - 如何将对象序列化为 json 并将其发送到 Web 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6535432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com