2012-05-18 78 views
4

我想將JSON發佈到WCF服務。 json對象包含一個數組。我想知道如何正確綁定到我的數據合同。如果任何人都可以在這裏給我一個指針,我會非常感激。目前我的購物車對象爲空WCF - 發佈JSON對象

這是我服務的接口是什麼樣子:

public interface IService 
{ 

[OperationContract] 
[WebInvoke(UriTemplate = "/cart", Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json)] 
Ship GetShipInfo(Cart cart, string Website); 
} 

[DataContract] 
public class Cart 
{ 
[DataMember] 
public Int32 ProductID { get; set;} 
[DataMember] 
public decimal ItemPrice { get; set; } 
[DataMember] 
public Int16 Qty { get; set; } 
[DataMember] 
public String SizeWidth { get; set; } 
} 

我的客戶呼叫如下

客戶端調用

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Runtime.Serialization.Json; 
using System.Net; 
using System.IO; 

public partial class _Default : System.Web.UI.Page 
{ 
protected void Page_Load(object sender, EventArgs e) 
{ 

DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(string)); 
Cart cart = new Cart{ ProductID = 1000, ItemPrice = Convert.ToDecimal(32.50), Qty = 1, SizeWidth = 「6M」 }; 
WebClient Proxy1 = new WebClient(); 
Proxy1.Headers["Content-type"] = 「application/json」; 
MemoryStream ms = new MemoryStream(); 
DataContractJsonSerializer serializerToUplaod = new DataContractJsonSerializer(typeof(Cart)); 
serializerToUplaod.WriteObject(ms, cart); 

byte[] data = Proxy1.UploadData(「http://localhost:54897/IphoneService.svc/cart」, 「POST」, ms.ToArray()); 
Stream stream = new MemoryStream(data); 
obj = new DataContractJsonSerializer(typeof(Ship)); 
var Ship = obj.ReadObject(stream) as Ship; 

} 

public class Ship 
{ 
public Decimal SecondDay { get; set; } 
public Decimal NextDay { get; set; } 
} 

public class Cart 
{ 

public Int32 ProductID { get; set; } 

public Decimal ItemPrice { get; set; } 

public Int16 Qty { get; set; } 

public String SizeWidth { get; set; } 
} 

} 

我的JSON看起來像這樣

{"cart": 
[ 
{"ProductID":2957, 
"Qty":1, 
"ItemPrice":60, 
"SizeWidth":"5M"} 
] 
} 
+0

我這個苦苦掙扎,以及(相關帖子和其他人在這裏輸入):https://stackoverflow.com/a/48906303/826308 –

回答

6

您的WCF REST方法應該從提琴手看起來像下面的原始請求:

POST http://localhost:54897/IphoneService.svc/cart HTTP 1.1 
Content-Type: application/json 
Host: localhost 

{"cart":{"ProductId":1,"ItemPrice":60,"Qty":1,"SizeWidth":"5M"},"Website":"sample website"} 

在JSON的響應看起來如下:

HTTP/1.1 200 OK 
Content-Type: application/json 
Content-Length: 30 

{"SecondDay":5.0, "NextDay":7.0}