下我可以說明確的工作。我只是測試它。對不起,它在vb.net中,但你應該明白了。
在服務器端: 在IService1.vb
Imports System.ServiceModel
Imports System.ServiceModel.Activation
Imports System.ServiceModel.Web
Namespace Webservices
<ServiceContract()>
Public Interface IService1
<OperationContract()> _
<WebInvoke(method:="POST", ResponseFormat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.WrappedRequest)> _
Function test(manageBusiness As ManagedBusiness) As string
End Interface
End Namespace
在Service1.svc.vb
Imports System.Runtime.Serialization
Imports System.ServiceModel.Activation
Namespace Webservices
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Required)>
Public Class Service1
Implements IService1
Public function test(manageBusiness As ManagedBusiness) As string Implements IService1.test
Return "done"
End function
End Class
<CollectionDataContract()>
Public Class Services
Inherits List(Of Service)
End Class
<DataContract()>
Public Class Service
<DataMember()>Public Property Name As String
<DataMember()>Public Property Desc As String
<DataMember()>Public Property LongTime As Integer
End Class
<DataContract()>
Public Class ManagedBusiness
<DataMember()>Public Property Name As String
<DataMember()>Public Property Desc As String
<DataMember()>Public Property Services As Services
End Class
End NameSpace
我有線了webconfig設置。並把這個jQuery AJAX調用在客戶端:
$("#btnTest").click(function() {
var services = [];
services.push({
Name: "aaaaaa",
Desc: "aaaaaa",
LongTime: 30
});
services.push({
Name: "aaaaaa1",
Desc: "aaaaaa",
LongTime: 30
});
var data = {};
data.manageBusiness = {
Name: "aaaaaa",
Desc: "aaaaaaaaaaaa",
Services: services
}
$.ajax({
type: "POST",
url: "http://localhost:64110/Webservices/Service1.svc/test",
dataType: "json",
contentType: "application/json; charset=utf-8",
async: true,
data: JSON.stringify(data),
success(msg) {
}
});
});
我可以確認所請求的有效載荷如下:
{"manageBusiness":{"Name":"aaaaaa","Desc":"aaaaaaaaaaaa","Services":[{"Name":"aaaaaa","Desc":"aaaaaa","LongTime":30},{"Name":"aaaaaa1","Desc":"aaaaaa","LongTime":30}]}}
和WCF服務反序列化一切就好了。我認爲你缺少的是[CollectionDataContract]屬性。
更新:我試圖刪除[CollectionDataContract]屬性,它仍然工作。所以我猜測,數據協定屬性僅用於序列化,而不是反序列化所需的(?)
它也沒有幫助。該列表繼續變爲空。 –
那麼,你的JSON表示形式良好,所以我不明白什麼是錯的,你能發送更多的代碼嗎?例如處理調用的c#代碼和發送請求的javascript代碼? –
它真的有用嗎?我也正在經歷同樣的情況!我需要這個代碼。 –